自动将单词转换为PHP中的链接 [英] automatic convert word to link in PHP
问题描述
如果不是链接,我想编写一个简单的代码将特殊词转换为特殊链接(对于Wiki插件)!
I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!
例如,假设我们有一个文本"Hello! How are you?!"
和
我们希望将are
转换为<a href="url">are</a>
,,但是如果我们拥有<a href="#"> Hello! How are you</a>?!
或Hello! <a href="url">How are you?!</a>
不变.因为它是一个链接.
For example suppose we have a text "Hello! How are you?!"
and
we want convert are
to <a href="url">are</a>
, but if we have <a href="#"> Hello! How are you</a>?!
or Hello! <a href="url">How are you?!</a>
does not change. Because it's a link.
如何在PHP中做到这一点?用preg_replace
?!怎么做?
How can I do it in PHP?! With preg_replace
?! How to?
谢谢.
推荐答案
为更好地阐明问题,
我有一个带有一些标签的HTML代码.我想要其中的一些单词,转换为一些链接.但是,如果是另一个链接,则不会转换.请参阅以下高级示例,获取要链接到 google 的特殊单词you
:
I have a HTML code that have some tags. I want some words in that, converted to some links. But if it is a another link does not convert. See below advanced example for special word you
that we want linked to the google:
This <a href="#">is a sample</a> text.
Hello?! How are you?!
<a href="#1">Are you ready</a>?!
This <a href="#">is a sample</a> text.
Hello?! How are you?!
<a href="#1">Are you ready</a>?!
应转换为:
This <a href="#">is a sample</a> text.
Hello?! How are <a href="http://www.google.com">you</a>?!
<a href="#1">Are you ready</a> ?!
This <a href="#">is a sample</a> text.
Hello?! How are <a href="http://www.google.com">you</a>?!
<a href="#1">Are you ready</a> ?!
注意 ,第一个you
已更改,但第二个you
未被更改,因为它位于另一个<a>
标记中.
Note that the first you
changed, but that second you
was not changed, because it's in the another <a>
tag.
答案:
由于这项工作存在正则表达式问题,因此无需正则表达式就可以解决此问题.这里给出一个简单的解决方案:
Because of this work has issue with regular expression, this problem can solve without regular expression. Here a simple solution is given:
$data = 'Hello! This is a sample text. <br/>'.
'Hello! This <a href="#1">is</a> a sample text. <br/>'.
'Hello! This <a href="#2">is a sample text.</a> <br/>'.
'Hello! <a href="#3">This is a sample</a> text. <br/>'.
'<a href="#4">Hello! This</a> is a sample text.';
$from = " is ";
$to = '<a href="http://www.google.com" > '.$from.' </a>';
echo $data;
$data = explode($from, $data);
echo "<br><br>";
echo $data[0];
$diff = 0;
for($i=1; $i<count($data); $i++){
$n = substr_count($data[$i-1], '<a ') + substr_count($data[$i-1], '<A ');
$m = substr_count($data[$i-1], '</a>') + substr_count($data[$i-1], '</A>');
$diff += $n-$m;
if($diff==0)
echo $to.$data[$i];
else
echo $from.$data[$i];
}
这篇关于自动将单词转换为PHP中的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!