我有一个大字符串,其中包含mysite/tim/here-is-something.html
其他 url 模式,例如mysite/a/some-thing.html
. 现在我想将第一个模式全部更改-
为+
并保持所有其他模式不变。
有谁知道如何处理这个问题?
感谢您的任何建议!
我有一个大字符串,其中包含mysite/tim/here-is-something.html
其他 url 模式,例如mysite/a/some-thing.html
. 现在我想将第一个模式全部更改-
为+
并保持所有其他模式不变。
有谁知道如何处理这个问题?
感谢您的任何建议!
$pattern = '!((mysite/tim/)[-\w\.]*)+(?=((mysite/a/)+)|(\s+|\n))!';
$html = 'mysite/tim/here-is-something.html mysite/tim/here-is-something.html mysite/a/here-is-something.html mysite/tim/here-is-som-ething.html mysite/a/here-is-something.html mysite/tim/he-re-is-so-m-eth-ing.html mysite/a/here-is-something.html mysite/a/here-is-something.html mysite/tim/here-is-something.html mysite/tim/here-is-something.html
mysite/tim/here-is-something.html ';
preg_match_all($pattern,$html, $match);
//print_r($match);
foreach ($match[0] as $value) {
$modified_value=str_replace("-","+", $value);
$html=str_replace($value,$modified_value,$html);
}
print_r ($html);
输出:
mysite/tim/here+is+something.html mysite/tim/here+is+something.html mysite/a/here-is-something.html mysite/tim/here+is+som+ething.html mysite/a/here-is-something.html mysite/tim/he+re+is+so+m+eth+ing.html mysite/a/here-is-something.html mysite/a/here-is-something.html mysite/tim/here+is+something.html mysite/tim/here+is+something.html mysite/tim/here+is+something.html
找到的匹配项:
match[0] => Array
(
[0] => mysite/tim/here-is-something.html
[1] => mysite/tim/here-is-something.html
[2] => mysite/tim/here-is-som-ething.html
[3] => mysite/tim/he-re-is-so-m-eth-ing.html
[4] => mysite/tim/here-is-something.html
[5] => mysite/tim/here-is-something.html
[6] => mysite/tim/here-is-something.html
)
听起来您已经解决了它,但问题被巧妙地分为 preg_match 和 str_replace。preg_match 可能比您描述的将元素加载到数组中更灵活,但它也需要了解正则表达式才能理解它的工作原理。
preg_replace 不能用于一步实现此结果,因为它无法处理灵活长度的正向后视。它可以替换一次出现 - 但不能替换多次出现(除非它被放入 while 循环,这将是另一种选择)。
<?
$strings = array("mysite/tim/here-is-something.html",
"mysite/a/some-thing.html");
foreach ($strings as $string) {
if (preg_match("#^(mysite/tim/)(.*)#",$string,$matches)) {
print "Changed string: $string\nto: ";
print $matches[1].str_replace("-","+",$matches[2])."\n";
} else {
print "Didn't change string: $string\n";
}
}
输出:
Changed string: mysite/tim/here-is-something.html
to: mysite/tim/here+is+something.html
Didn't change string: mysite/a/some-thing.html