PHP-用超链接替换字符串中的各种大小写类型并保留原始大小写

PHP-用超链接替换字符串中的各种大小写类型并保留原始大小写,php,Php,我有以下字符串: “这是包含三个MYTEXT实例的字符串。这是第一个实例。这是MYTEXT的第二个实例。这是MYTEXT的第三个实例。” 我需要将Mytext的每个实例(所有三个实例)替换为包装在标记中的版本,因此我希望在每个实例周围包装HTML标记。这很容易,我做这件事没有问题。我的问题是——在保留每个实例的原始案例的同时,如何做到这一点。我需要的输出是: “这是包含三个MYTEXT实例的字符串。这是第一个实例。这是MYTEXT的第二个实例。这是MYTEXT的第三个实例。” 我一直在看Stru

我有以下字符串:

“这是包含三个MYTEXT实例的字符串。这是第一个实例。这是MYTEXT的第二个实例。这是MYTEXT的第三个实例。”

我需要将Mytext的每个实例(所有三个实例)替换为包装在标记中的版本,因此我希望在每个实例周围包装HTML标记。这很容易,我做这件事没有问题。我的问题是——在保留每个实例的原始案例的同时,如何做到这一点。我需要的输出是:

“这是包含三个MYTEXT实例的字符串。这是第一个实例。这是MYTEXT的第二个实例。这是MYTEXT的第三个实例。”

我一直在看Stru_ireplace和preg_teplace,但他们似乎都没有做这项工作

有什么想法吗


提前谢谢

您可以使用反向引用来完成此操作:

preg_replace('/mytext/i', '<a href="foo.html">\\0</a>', $str);
preg_替换('/mytext/i','$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.

?>

注意:正如我在开始时所暗示的,这种方法使用了糟糕的编程实践