hamlet
hamlet

Reputation:

Simple regular expression replacing colons

I need a simple regexp for php preg_replace:

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

:something: to !|something|!

Upvotes: 0

Views: 87

Answers (3)

cletus
cletus

Reputation: 625097

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);

Upvotes: 0

Paige Ruten
Paige Ruten

Reputation: 176675

$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.

Upvotes: 2

Gumbo
Gumbo

Reputation: 655309

Try this:

$str = preg_replace('/:([^:]+):/', '!|\\1|!', $str);

Upvotes: 2

Related Questions