Jump to content

change a string with PREG_REPLACE


dr3ex

Recommended Posts

I'm having hard time with PREG_REPLACE.

 

I have this string ($str):

test \"first string\" test \"second string longer\" end

 

I need to have:

%test%first string%test%second string longer%end%

 

This doesn't work:

echo preg_replace('#(")(.*?)(")#i', '%$2%', stripslashes($str));

 

Result:

test %first string% test %second string longer% end

 

Thanks all for help!

Link to comment
https://forums.phpfreaks.com/topic/274292-change-a-string-with-preg_replace/
Share on other sites

What you want to match is a quote, which is either followed by or following a space. Since I assume that he order and number of matching characters isn't significant (other than being at least 2), this can be done quite simple:

$RegExp = '#[" ]{2,}(\w+)[" ]{2,0}#';
$str = preg_replace ($RegExp, '%$1%', $str);

This would match two or more of any combination of spaces and quotes, followed by a a "word" consisting of one or more characters (captured), followed by the first combination.

 

As for the stripslashes (): You should never need to use this in your code, as it is an indicator of something being either unnecessary escaped or doubly-escaped. Make sure that "magic_quotes" is turned off, and that you're not using any functions that adds slashes before this point.

Thank you, but it doesn't work:

 

$str = 'test "first string" test "second string longer" end';
$RegExp = '#[" ]{2,}(\w+)[" ]{2,0}#';
$str = preg_replace($RegExp, '%$1%', $str); // Error line
echo $str;

 

Warning: preg_replace() [function.preg-replace]: Compilation failed: numbers out of order in {} quantifier at offset 21 in C:\...\script.php on line Error line

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.