与preg_replace和php中的类似单词有问题 [英] having issue with preg_replace and similar words in php

查看:51
本文介绍了与preg_replace和php中的类似单词有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想搜索我的字符串,并通过链接到某些页面来替换某些单词. 但是我对类似帮助"和帮助我"这样的词有疑问. 我想链接帮助我"而不是帮助". 这是我的代码:

i want to search my string and replace some words by link to some page. but i have problem with similar words like "Help" and "Help Me". i want to link "Help Me" not "Help". this is my code:

$text="Please Help Me Fix This Issue!";
$AllTags=[];
$AllTags[]='Help';
$AllTags[]='Help Me';
    $tmp = array();
    foreach($AllTags as $term){
        $tmp[] = "/($term)/i";
    } 
echo preg_replace($tmp, '<a href="$0">$0</a>', $text);

推荐答案

这是一种动态方法:按照值长度的降序对数组进行排序,然后将implode|组合为基于交替的模式,以便较长的部分将首先匹配(请记住,匹配的左侧第一个分支使正则表达式停止分析替代项,请参见 请记住,正则表达式引擎是渴望的 ).

Here is the dynamic approach: sort the array by value length in a descending order, then implode with | into an alternation based pattern so that the longer parts will be matched first (remember that the first branch from the left that matches makes the regex stop analyzing the alternatives, see Remember That The Regex Engine Is Eager).

使用

$text="Please Help Me Fix This Issue!";
$AllTags=[];
$AllTags[]='Help';
$AllTags[]='Help Me';
usort($AllTags, function($a, $b) {
    return strlen($b) - strlen($a);
});
echo preg_replace('~' . implode('|', $AllTags) . '~', '<a href="$0">$0</a>', $text);

请参见 PHP演示.

正则表达式将类似于 ~Help Me|Help~ .您可能想添加单词边界(\b)(参见演示)或类似(?<!\S)(?!\S)(见演示)只能在以后匹配整个单词.

The regex will look like ~Help Me|Help~. You might want to add word boundaries (\b) (see demo) or lookarounds like (?<!\S) and (?!\S) (see demo) to only match whole words later.

这篇关于与preg_replace和php中的类似单词有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆