Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP pregreplace将文本中的特定单词转换为链接(如果它们不是';t已创建链接并添加锚文本_Php - Fatal编程技术网

使用PHP pregreplace将文本中的特定单词转换为链接(如果它们不是';t已创建链接并添加锚文本

使用PHP pregreplace将文本中的特定单词转换为链接(如果它们不是';t已创建链接并添加锚文本,php,Php,与stackoverflow上的what’s和许多其他地方类似,但有一个转折点 假设我的页面上有一句话“我喜欢棕色的狗”。我想在输出之前处理这个文本,并查找单词brown。如果brown已经是链接的一部分(包装在a标记中),则什么也不做。但是,如果它不在链接中,请使用我的预定义代码作为替换 我的代码是这样的: <a href="/brown" title="Looking for the color brown?">brown</a> 我甚至不知道我是否解释得足够好,或

与stackoverflow上的what’s和许多其他地方类似,但有一个转折点

假设我的页面上有一句话“我喜欢棕色的狗”。我想在输出之前处理这个文本,并查找单词brown。如果brown已经是链接的一部分(包装在a标记中),则什么也不做。但是,如果它不在链接中,请使用我的预定义代码作为替换

我的代码是这样的:

<a href="/brown" title="Looking for the color brown?">brown</a>
我甚至不知道我是否解释得足够好,或者这是否可能,但如果是,请让我知道。谢谢


编辑:我找到了一个和我想要的很接近的,并且让它在某种程度上发挥了作用。问题是我不能限制替换的数量,比如每页只做一次,或者每页两次。理想情况下,我想告诉它忽略它,如果它在H标签。嗨,milki.

如果您想重写HTML上下文感知,那么实际上使用DOM函数更容易。您仍然需要regex或string函数来重写文本节点,因此需要编写更多的代码

但是一个简单的解决方法是使用。只需匹配不需要的标记,然后在回调中忽略它们

preg_replace_callback('%(<h)\d>.*?</h\d>|Amazon(?![^<]*</a>)%si',
                      'replace_cb_words', ...

function replace_cb_words($match) {

     // ignore the <h1>... matches
     if ($match[1]) return $match[0];

     // rewrite the words otherwise:
     return "<a ...>$match[0]</a>";
}

preg_replace_回调('%(.*)Amazon(?[^标记可能重复。(php)或者顺便说一句,你可以很容易地对链接到的答案或任何其他
preg\u replace
的替换次数添加一个限制。请参见
limit
中的参数“是”,我找到了limit参数,这就是为什么我从原始问题中删除了它。我的问题与任何其他问题之间的差异,我可以在这里找到(我读过15篇)是为了确保它不在某种类型的标签中,比如blockquote或H3。
preg_replace_callback('%(<h)\d>.*?</h\d>|Amazon(?![^<]*</a>)%si',
                      'replace_cb_words', ...

function replace_cb_words($match) {

     // ignore the <h1>... matches
     if ($match[1]) return $match[0];

     // rewrite the words otherwise:
     return "<a ...>$match[0]</a>";
}