有一個包含數字數據的字符串變量,如$x = "OP/99/DIR";
。數字數據的位置可以在任何情況下通過用戶需求在應用程序內部修改而改變,並且斜槓可以被任何其他字符改變;但號碼數據是強制性的。如何將數字數據替換爲不同的數字?示例OP/99/DIR
更改爲OP/100/DIR
。如何將字符串中的數字數據替換爲不同的數字?
1
A
回答
2
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);
print $string;
輸出:
OP/100/DIR
2
假設的數目只發生一次:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);
只改變第一次出現:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);
2
使用正則表達式和的preg_replace
$x="OP/99/DIR";
$new = 100;
$x=preg_replace('/\d+/e','$new',$x);
print $x;
1
最靈活的解決方案是使用preg_replace_callback(),所以你可以做任何你想要的比賽。這匹配字符串中的單個數字,然後將其替換爲數字加1。
[email protected]:~# more test.php
<?php
function callback($matches) {
//If there's another match, do something, if invalid
return $matches[0] + 1;
}
$d[] = "OP/9/DIR";
$d[] = "9\$OP\$DIR";
$d[] = "DIR%OP%9";
$d[] = "OP/9321/DIR";
$d[] = "9321\$OP\$DIR";
$d[] = "DIR%OP%9321";
//Change regexp to use the proper separator if needed
$d2 = preg_replace_callback("(\d+)","callback",$d);
print_r($d2);
?>
[email protected]:~# php test.php
Array
(
[0] => OP/10/DIR
[1] => 10$OP$DIR
[2] => DIR%OP%10
[3] => OP/9322/DIR
[4] => 9322$OP$DIR
[5] => DIR%OP%9322
)
它和alexey的回答非常相似,所以使用'!'有什麼區別? – pheromix 2012-07-12 10:54:01
我使用了e修飾符,以便您可以在第二個參數中執行任何操作。關於!,實際上沒有什麼區別。它只是一個分隔符。檢查http://www.php.net/manual/en/regexp.reference.delimiters.php。 – Jithin 2012-07-12 11:00:09