...

View Full Version : preg_replace() Unknown modifier



Aargh
11-23-2011, 04:31 PM
Hello everyone

I have a problem with preg_replace(). It's probably something stupid that I simply fail to see, but I can't figure out what's wrong.

The thing is, I have a string that has a lot of information I don't need, and I use preg_replace to strip that out.

For this, I use the following code:


$regex = "'?;? ?option\['\d+'\] = '";
$replace = ", ";

echo preg_replace($regex, $replace, $string);


I tested this using http://gskinner.com/RegExr/ to be sure the regular expression isn't wrong. On that page it works exactly the way I want it to work, but when I use it in my PHP code it tells me
Warning: preg_replace() [function.preg-replace]: Unknown modifier '\' in **filename** on line 13

Can anyone tell me what I'm doing wrong, and more importantly how to do it right?

Fou-Lu
11-23-2011, 04:38 PM
PCRE regex must be delimited (http://php.ca/manual/en/regexp.reference.delimiters.php) in order to use.


For further explanation as to what the problem is, it considers your ' as a delimiter. Therefore, all characters found after the delimiter need to be modifiers, which \ is not.

Aargh
11-23-2011, 04:51 PM
Ah, I understand. Thank you for that link.

However, now it seems like I have a new problem. I changed the code to $regex = "{'?;? ?option\['\d+'\] = '}"; to include the delimiter, but now it seems I have another problem: the '?;? ? part of the expression seems to be ignored completely.

Fou-Lu
11-23-2011, 04:56 PM
What are you trying to match against?

Aargh
11-23-2011, 05:07 PM
The string I recieve is basically
option['34'] = 'sometext'; option['3'] = 'someothertext'; option['9000'] = 'moretext'; option['42'] = 'texttexttext';
and so on. For this function I just want to have
sometext, someothertext, moretext, texttexttext
I get the original string from a different function I'm not allowed to touch at all (it's not mine), so I figure I'd just strip out the parts I don't need with preg_replace().

I realize this is probably not the best way to do it since it leaves some junk at the beginning and the end of the string, but as long as it's only the beginning and the end I can just substr() it away and still end up with exactly what I need.

Fou-Lu
11-23-2011, 05:32 PM
Works for me. You'll need to ltrim off the ', ' from the string though since it replaces it otherwise.
I used this: $pattern = "{'?;?\s*option\['\d+'\] = '}";

Aargh
11-23-2011, 05:40 PM
Now it works, thanks for your help. I guess the problem was ? vs \s*.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum