PHP 将单词替换为除图像之外的链接 [英] PHP replace words to links except images

查看:30
本文介绍了PHP 将单词替换为除图像之外的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是

$words = array();
$links = array();
$result = mysql_query("SELECT `keyword`, `link` FROM `articles` where `link`!='".$act."' ") 
or die(mysql_error());
$i = 0;
while($row = mysql_fetch_array( $result )) 
{
if (!empty($row['keyword']))
{
$words[$i] = '/(?<!(src="|alt="))'.$row['keyword'].'/i';
$links[$i] = '<a href="'.$row['link'].'.html" class="ared">'.$row['keyword'].'</a>';
$i++;
}
}
$text = preg_replace($words, $links, $text);

我想用除了 img src 和 alt 之外的 Guys 替换 Hello.

I want to replace Hello with Guys except img src and alt.

来自

Say Hello my dear <img src="say-hello-my-dear.jpg" alt="say hello my dear" />

我想要

Say Guys my dear <img src="say-hello-my-dear.jpg" alt="say hello my dear" />

当前代码,仅当我的关键字只有 1 个字时才替换.

The current code, replaces only when my keyword has only 1 word.

推荐答案

我不敢相信我花了这么长时间才明白您正在尝试使用正则表达式解析大块 HTML.阅读这个问题的答案:正则表达式匹配除 XHTML 自包含标签之外的开放标签

I can't believe it took me that long to understand that you're trying to parse big chunks of HTML with regular expressions. Read the answer to this question: RegEx match open tags except XHTML self-contained tags

这篇关于PHP 将单词替换为除图像之外的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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