开发者

Reverse String Using Regexes

开发者 https://www.devze.com 2023-02-05 07:38 出处:网络
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?

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>", s开发者_JAVA百科trrev($1), $str), but for obvious reasons, that didn't work.


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消