nie*_*lsv 2 php replace preg-replace
这就是我现在所做的:
if (strpos($routeName,'/nl/') !== false) {
$routeName = preg_replace('/nl/', $lang , $routeName, 1 );
}
Run Code Online (Sandbox Code Playgroud)
我替换了nlfor for ex.de.但现在我想取代second occurrence.最简单的方法是什么?
@Casimir的答案似乎适用于大多数情况.另一种选择是preg_replace_callback使用计数器.如果您需要仅更换特定的第n次出现.
#-- regex-replace an occurence by count
$s = "…abc…abc…abc…";
$counter = 1;
$s = preg_replace_callback("/abc/", function ($m) use (&$counter) {
#-- replacement for 2nd occurence of "abc"
if ($counter++ == 2) {
return "def";
}
#-- else leave current match
return $m[0];
}, $s);
Run Code Online (Sandbox Code Playgroud)
这利用了本地$counter,在每次出现的回调中递增,并且在这里简单地检查固定位置.
因此,首先检查是否有任何情况发生,如果有,则将其替换。您可以计算出现次数(unsing substr_count)来了解其中存在多少个。然后,如果需要的话,只需一点一点地替换它们即可。
$occurrences = substr_count($routeName, '/nl/');
if ($occurrences > 0) {
$routeName = preg_replace('/nl/', $lang , $routeName, 1 );
if ($occurrences > 1) {
// second replace
$routeName = preg_replace('/nl/', $lang , $routeName, 1 );
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想替换第二个出现的地方(如您稍后在注释中所述),请查看substr并阅读PHP 中的字符串函数。您可以使用第一个出现的地方,strpos作为 substr 的开始,然后将其用于替换。
<?php
$routeName = 'http://example.nl/language/nl/peter-list/foo/bar?example=y23&source=nl';
$lang = 'de';
$routeNamePart1 = substr( $routeName, 0 , strpos($routeName,'nl') +4 );
$routeNamePart2 = substr( $routeName, strpos($routeName,'nl') + 4);
$routeNamePart2 = preg_replace('/nl/', $lang , $routeNamePart2, 1 );
$routeName = $routeNamePart1 . $routeNamePart2;
echo $routeName;
Run Code Online (Sandbox Code Playgroud)
在这里查看这个工作。
| 归档时间: |
|
| 查看次数: |
8015 次 |
| 最近记录: |