我有以下字符串:
"这是我的字符串,包含三个MYTEXT实例。这是第一个例子。这是Mytext的第二个实例。这是mytext的第三个实例。"
我需要用标签包装的版本替换Mytext的每个实例(所有三个实例),所以我想在每个实例周围包装HTML标签。这很容易,我做这件事没有问题。我的问题是-我如何做到这一点,同时保留每个实例的原始情况。我需要的输出是:
"这是我的字符串,包含三个MYTEXT实例。这是第一个例子。这是Mytext的第二个实例。这是mytext的第三个实例。"
我一直在看str_ireplace和preg_teplace,但他们似乎都没有做这项工作。
任何想法?
提前感谢。
您可以使用反向引用来完成此操作:
preg_replace('/mytext/i', '<a href="foo.html">''0</a>', $str);
替换字符串中的''0
反向引用将被替换为整个匹配,有效地保持了原始情况
使用基础知识的另一种效率低得多的解决方案。
<?php
$string = "This is my string with three instances of MYTEXT. That was the first instance. This is the second instance of Mytext. And this is the third instance of mytext.";
$copyOfString = $string; // A copy of the original string, so that you can use the original string later.
$matches = array(); // An array to fill with the matches returned by the PHP function using Regular Expressions.
preg_match_all("/mytext/i", $string, $matches); // The above-mentioned function. Note that the 'i' makes the search case-insensitive.
foreach($matches as $matchSubArray){
foreach($matchSubArray as $match){ // This is only one way to do this.
$replacingString = "<b>".$match."</b>"; // Edit to use the tags you want to use.
$copyOfString = str_replace($match, $replacingString, $copyOfString); // str_replace is case-sensitive.
}
}
echo $copyOfString; // Output the final, and modified string.
?>
注意:正如我在开头所暗示的,这种方法使用了糟糕的编程实践。