たとえば、数値データを含む文字列変数があります$x = "OP/99/DIR";
。数値データの位置は、アプリケーション内で変更することにより、ユーザーの希望により任意の状況で変更できます。また、スラッシュ バーは他の文字で変更できます。ただし、数値データは必須です。数値データを別の数値に置き換える方法は? 例OP/99/DIR
は に変更されOP/100/DIR
ます。
質問する
111 次
4 に答える
2
数値が 1 回だけ発生すると仮定すると、次のようになります。
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);
最初のオカレンスのみを変更するには:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);
于 2012-07-12T10:44:38.630 に答える
2
正規表現と preg_replace の使用
$x="OP/99/DIR";
$new = 100;
$x=preg_replace('/\d+/e','$new',$x);
print $x;
于 2012-07-12T10:46:46.300 に答える
2
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);
print $string;
出力:
OP/100/DIR
于 2012-07-12T10:46:58.197 に答える
1
最も柔軟な解決策は、 preg_replace_callback() を使用することです。そうすれば、一致したものを好きなように処理できます。これは、文字列内の単一の数値に一致し、その数値に 1 を加えたものに置き換えます。
root@xxx:~# 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);
?>
root@xxx:~# 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
)
于 2012-07-12T10:50:16.450 に答える