PHP正则表达式以匹配HTML标签之外的关键字

PHP正则表达式以匹配HTML标签之外的关键字,第1张

PHP正则表达式以匹配HTML标签之外的关键字

我设法通过以下方式完成了我想做的事情( 不使用Regex ):

  • 解析字符串的每个字符
  • 删除所有
    <a>
    标签(将它们复制到临时数组并在字符串上保留占位符)
  • str_replace
    新字符串以替换所有关键字
  • 通过原始
    <a>
    标签重新填充占位符

如果有人需要,这是我使用的代码:

$str = <<<STRAMoses supposes his toeses are roses,but <a href="original-moses1.html">Moses</a> supposes erroneously;for nobody's toeses are posies of roses,as Moses supposes his toeses to be.Ganda <span ><a href="original-moses2.html" target="_blank">Moses</a></span>!STRA;$arr1 = str_split($str);$arr_links = array();$phrase_holder = '';$current_a = 0;$goto_arr_links = false;$close_a = false;foreach($arr1 as $k => $v){    if ($close_a == true)    {        if ($v == '>') { $close_a = false;        }         continue;    }    if ($goto_arr_links == true)    {        $arr_links[$current_a] .= $v;    }    if ($v == '<' && $arr1[$k+1] == 'a') {         // keep collecting every char until </a>        $arr_links[$current_a] .= $v;        $goto_arr_links = true;    } elseif ($v == '<' && $arr1[$k+1] == '/' && $arr1[$k+2] == 'a' && $arr1[$k+3] == '>' ) {         $arr_links[$current_a] .= "/a>";        $goto_arr_links = false;        $close_a = true;        $phrase_holder .= "{%$current_a%}";         $current_a++;    }        elseif ($goto_arr_links == false) {        $phrase_holder .= $v;    }}echo "links Array:n";print_r($arr_links);echo "nnnPhrase Holder:n";echo $phrase_holder;echo "nnn(pre) Final Phrase (with my keyword replaced):n";$final_phrase = str_replace("Moses", "<a href="novo-mega-link.php">Moses</a>", $phrase_holder);echo $final_phrase;echo "nnnFinal Phrase:n";foreach($arr_links as $k => $v){    $final_phrase = str_replace("{%$k%}", $v, $final_phrase);}echo $final_phrase;

输出:

链接数组:

Array(    [0] => <a href="original-moses1.html">Moses</a>    [1] => <a href="original-moses2.html" target="_blank">Moses</a>)

词组

Moses supposes his toeses are roses,but {%0%} supposes erroneously;for nobody's toeses are posies of roses,as Moses supposes his toeses to be.Ganda <span >{%1%}</span>!

(上)最终词组(替换为我的关键字):

<a href="novo-mega-link.php">Moses</a> supposes his toeses are roses,but {%0%} supposes erroneously;for nobody's toeses are posies of roses,as <a href="novo-mega-link.php">Moses</a> supposes his toeses to be.Ganda <span >{%1%}</span>!

最终词组:

<a href="novo-mega-link.php">Moses</a> supposes his toeses are roses,but <a href="original-moses1.html">Moses</a> supposes erroneously;for nobody's toeses are posies of roses,as <a href="novo-mega-link.php">Moses</a> supposes his toeses to be.Ganda <span ><a href="original-moses2.html" target="_blank">Moses</a></span>!


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5427512.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存