PHP正则内链排除alt的方法

WBOY
Release: 2016-06-20 12:29:49
Original
2183 people have browsed it

PHP 现在要实现内链功能, 替换关键词为 a标签, 但是alt中也会有关键词 替换后就会导致出错,   

我想把alt中的关键词替换成其他字符在完成内链后在替换回来

$newsinfo[content]=preg_replace("/(?<=alt=\".*)(格斗江湖)(?=.*\")/","&&&&%%%%","<img alt=\"113453451格斗江湖56546456546\"");
Copy after login

但是这样写的话好像没有匹配出来,我在正则工具中测试没有问题. 是我写的正则有问题吗? 还有什么方法实现呢 谢谢.


回复讨论(解决方案)

php 的 (?<=pattern) 断言 是定长的
而你些的是不定长的 (?<=alt=\" .*)

echo preg_replace('/alt=".+?(格斗江湖).+?"/',"&&&&%%%%",'113453451格斗江湖56546456546');

echo preg_replace('/alt=".+?(格斗江湖).+?"/',"&&&&%%%%",'113453451格斗江湖56546456546');


这样的话把整个alt替换了呢, 我只想替换 alt 中所含的关键词

php 的 (?<=pattern) 断言 是定长的
而你些的是不定长的 (?<=alt=\" .*)


那有什么办法实现,只替换 alt中 的关键词吗?

echo preg_replace('/alt="(.+?)(格斗江湖)(.+?)"/','alt="$1&&&&%%%%$3"','113453451格斗江湖56546456546');

$html = '<img alt="113453451格斗江湖56546456546">格斗江湖';echo preg_replace('#(?=[^>]*(?=<(?!/a>)|$))格斗江湖#','<a href="新加的链接.html">\0</a>',$html);
Copy after login
Copy after login
113453451格斗江湖56546456546格斗江湖

echo preg_replace('/alt="(.+?)(格斗江湖)(.+?)"/','alt="$1&&&&%%%%$3"','113453451格斗江湖56546456546');


谢谢你, PHP正则和其他的不一样吗? 我用正则工具匹配和php匹配结果不一样

$html = '<img alt="113453451格斗江湖56546456546">格斗江湖';echo preg_replace('#(?=[^>]*(?=<(?!/a>)|$))格斗江湖#','<a href="新加的链接.html">\0</a>',$html);
Copy after login
Copy after login
PHP正则内链排除alt的方法格斗江湖


谢谢 
php正则和其他的似乎有些不同吗?  这种差异在哪里讲, 或者那本书有写到这些知识呢, 麻烦您了

手册中有,不过是英文的
网上一些教程中也提及到


The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. 
一个追溯断言的内容限制,所有的字符串匹配的必须有一个固定的长度

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!