-1

I'm using preg_replace function to remove a list of stop words. Currently, I have an array containing a lst of stop words. As the parameter for preg_replace I use this as the first argument (i.e, preg_replace(^$stopwordlist$, '',$string) As you can see I'm also using ^$ as I need to match word exactly.However I'm getting the following error

syntax error, unexpected '^', expecting ')' in 

Thanks

Alma Do
  • 37,009
  • 9
  • 76
  • 105
user1926567
  • 153
  • 1
  • 3
  • 8
  • 2
    Need string, regex delimiters. – elclanrs Aug 28 '13 at 06:40
  • Please post your code here – Alex Aug 28 '13 at 06:41
  • 2
    Have you ever learned the basics of PHP ? Please start from [here](http://php.net/manual/en/language.types.string.php) – HamZa Aug 28 '13 at 06:41
  • @user1926567 what if you use this code `preg_replace('/^'.$stopwordlist.'$/', '',$string)` – zzlalani Aug 28 '13 at 06:47
  • ^ and $ don't work like you think they do. What you're really saying by including ^ at the beginning and $ at the end is that you want to replace it if the _ENTIRE VALUE OF $string_ matches what you're passing to it. Put a space before and after each element in the `$stopwordlist` array, and do away with the ^ and $ – DiMono Aug 28 '13 at 06:48

3 Answers3

1

If $stopwordlist is an array you might want to implode() it first.

As for the syntax error, you need to put the ^ and $ in quotes, you're also missing delimiters in your regex.

Change your code to something like this:

// Implode with a |, which is basically an 'or' statement is regex
$pattern = '/^' . implode('|', $stopwordlist) . '$/';

// Replace them
$replaced = preg_replace($pattern, '', $string);

If you need a place to test your regular expression, try gskinner.com's RegExr.

MisterBla
  • 2,355
  • 1
  • 18
  • 29
0

If you want to match exact words, REG EXPs and preg_replace are not what you need.

Give a look at str_replace or strtr documentation to find out which one you need.

http://www.php.net/manual/en/function.str-replace.php

http://www.php.net/manual/en/function.strtr.php

Clément Malet
  • 5,062
  • 3
  • 29
  • 48
0

You can use

$string=str_replace($stopwordlist, "", $string);
Nanhe Kumar
  • 15,498
  • 5
  • 79
  • 71