Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.