Replace Exact Occurrence of Word in PHP?

后端 未结 3 1575
耶瑟儿~
耶瑟儿~ 2021-01-14 18:46

I need to repeatedly remove certain stop words from articles. Currently I am using the function str_replace to achieve this. As the first argument I use the stop list array

相关标签:
3条回答
  • 2021-01-14 19:28

    This should work:

    $i = $string;
    foreach($swarray as $word) {
      $i = str_replace(" " . $word . " ", "", $i );
    }
    
    0 讨论(0)
  • 2021-01-14 19:46

    preg_replace with array

    $find = array('/\bth\b/', '/\bthe\b/', '/\bthen\b/');
    $replace = array('', '', '');
    
    echo $i = preg_replace($find, $replace, $string);
    

    Or

    $find = array('/\bth\b/', '/\bthe\b/', '/\bthen\b/');
    
    echo $i = preg_replace($find, "", $string);
    

    Regex match document: http://www.php.net/manual/en/function.preg-replace.php#89364

    \b Match a word boundary
    
    0 讨论(0)
  • 2021-01-14 19:49

    You need to instead use preg_replace with word boundaries. For example below we're only replacing word the while avoiding replacing them or then etc

    $string = preg_replace('/\bthe\b/', '', $string);
    
    0 讨论(0)
提交回复
热议问题