[英]How to replace 2 strings (with eachother) simultaneously in PHP
我想要做的很簡單,但我希望最有效地做到這一點,最好使用php內置的fns。
$str = '1234';
echo replace_function(array('1','3'),array('3','1'),$str);
// output: 3214
str_replace,preg_replace將導致1214,這意味着它將通過數組,替換匹配的字符串。 我正在尋找一種同時“切換”這兩個(或更多)字符串的解決方案。
有任何想法嗎?
你需要字符串翻譯: 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);
?>
您可以將模式更改為更通用的模式,例如'/(\\ d)(\\ d)(\\ d)(\\ d)/'。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.