tags:

views:

59

answers:

3

Hi,

I would need a simple regexp urgently for php preg_replace:

Input: Quick brown :no: fox etc Output: Quick brown !|no|! fox etc

:something: to !|something|!

Thanks

+2  A: 

Try this:

$str = preg_replace('/:([^:]+):/', '!|\\1|!', $str);
Gumbo
+2  A: 
$output = preg_replace('/:([^ ]+):/', '!|$1|!', $input);

You might want to replace [^ ] with a more specific set, depending on what you are expecting to be in between the :s.

yjerem
Thanks, works great
hamlet
if you want more than one word between the colons to be replaced like that, use Gumbo's code (or replace `[^ ]` with `[^:]`)
yjerem
A: 

That depends on if a space is allowed between the colons. If it isn't:

$out = preg_replace('!:([^ ]+):!', '!|$1|!', $in);

is fine. You may also want to consider using a non-greedy expression instead:

$out = preg_replace('!:(.+?):!', '!|$1|!', $in);

Here is another option:

$out = preg_replace('!:([^:]+):!', '!|$1|!', $in);
cletus