开发者

How to replace 2 strings (with eachother) simultaneously in PHP

开发者 https://www.devze.com 2022-12-20 17:38 出处:网络
What I\'m t开发者_运维百科rying to do is very simple, but I\'m looking to do it most efficiently, preferably using php builtin fns.

What I'm t开发者_运维百科rying to do is very simple, but I'm looking to do it most efficiently, preferably using php builtin fns.

$str = '1234';
echo replace_function(array('1','3'),array('3','1'),$str);

// output: 3214

str_replace,preg_replace would result in 1214, which means it goes through the arrays, replacing matched strings. I'm looking for a solution to simultaneously "switch" these two (or more) strings.

any ideas?


You need string translate: http://php.net/manual/en/function.strtr.php

<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
// = hello all, I said hi
?> 


<?php

$subject = '1234';
$result = preg_replace('/(1)(2)(3)(4)/si', '$3$2$1$4', $subject);
var_dump($result);

?>

You can change the pattern to something more generic, such as '/(\d)(\d)(\d)(\d)/'.

0

精彩评论

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

关注公众号