简体   繁体   English

如何在PHP中同时替换2个字符串(相互之间)

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

What I'm trying to do is very simple, but I'm looking to do it most efficiently, preferably using php builtin fns. 我想要做的很简单,但我希望最有效地做到这一点,最好使用php内置的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. str_replace,preg_replace将导致1214,这意味着它将通过数组,替换匹配的字符串。 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 你需要字符串翻译: 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)/'. 您可以将模式更改为更通用的模式,例如'/(\\ d)(\\ d)(\\ d)(\\ d)/'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM