我有一个包含mysite/tim/here-is-something.html
的大字符串和其他网址格式,例如mysite/a/some-thing.html
。现在我想将第一个模式的所有-
更改为+
,并保持所有其他模式不变。
任何人都知道如何处理这个问题?
感谢您的任何建议!
答案 0 :(得分:0)
听起来你已经解决了,但问题整齐地分为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
答案 1 :(得分:0)
$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
)