Waleed Khan
Waleed Khan

Reputation: 11467

Reverse String Using Regexes

If I had a string like <start_delim>asdf<end_delim> and I wanted to take an alphanumeric string between the delimiters and reverse it using regexes, how would I go about doing this?

My natural instinct was to use something like preg_replace("<start_delim>([a-zA-Z0-9]+)<end_delim>", strrev($1), $str), but for obvious reasons, that didn't work.

Upvotes: 0

Views: 839

Answers (3)

rubber boots
rubber boots

Reputation: 15184

Somebody pointed out in a comment it'd be better not to use the /e modifier, but if possible, that would work. Almost exactly as you thought:

echo preg_replace('|<start_delim>([^<^]+)<end_delim>|e', 'strrev("$1")', $str);

Regards

rbo

Upvotes: -1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

Similar to previous solutions, but using a lambda:

$str = "<start_delim>asdf<end_delim>";
$result = preg_replace_callback('/<start_delim>([a-zA-Z0-9]+)<end_delim>/', function($matches) {
        return strrev($matches[1]);
}, $str);

echo "$result\n";

Upvotes: 0

Dogbert
Dogbert

Reputation: 222128

You'll have to use preg_replace_callback

$str = "<start_delim>asdf<end_delim>";
function my_callback($m) {
  return $m[1].strrev($m[2]).$m[3];
}
echo preg_replace_callback("/(<start_delim>)([a-zA-Z0-9]+)(<end_delim>)/", 'my_callback' , $str);

http://codepad.org/xP2arFZk

Upvotes: 4

Related Questions