使用preg_match的RegEx查找和替换类似字符串 [英] RegEx with preg_match to find and replace a SIMILAR string

查看:113
本文介绍了使用preg_match的RegEx查找和替换类似字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在preg_replace()中使用正则表达式,以便在一段文本中查找和替换一个句子. $search_string包含纯文本+ html标记+  元素.问题在于,只有 元素有时会在运行时转换为空白,这使得使用str_replace()进行查找和替换变得困难.因此,我正在尝试构建一个与搜索字符串相同的模式,并将匹配包含或不包含 元素的任何类似内容;

I am using regular expressions with preg_replace() in order to find and replace a sentence in a piece of text. The $search_string contains plain text + html tags +   elements. The problem is that only sometimes the   elements convert to white space on run time, making it difficult to find and replace using str_replace(). So, I'm trying to build a pattern that is equal to the search string and will match anything like it which contains, or does not contain the   elements;

例如:

$search_string = 'Two years in,&nbsp;the company has expanded to 35 cities, five of which are outside the U.S. Plus,&nbsp;in&nbsp;April, <a href="site.com">ClassPass</a> acquired its main competitor,&nbsp;Fitmob.';

$pattern = $search_string(但忽略主题中的&nbsp;元素)

$pattern = $search_string(BUT IGNORE THE &nbsp; elements in the subject)

$subject = "text text text text text". $search_string . "text text text text text";

使用正则表达式来排除单词/字符串,我尝试过:

     $pattern = '`^/(?!\&nbsp;)'.$search_string.'`';
     $output = preg_replace($pattern, $replacement_string,$subject);

最终结果将是,如果$ subject确实包含一个类似于我的$seach_string但没有&nbsp;元素的字符串,它将仍然匹配并替换为$replacement_string

The end result will be that if the $subject does contains a string that is like my $seach_string but without the &nbsp; elements, it will still match and replace it with $replacement_string

实际值:

$subject = file_get_contents("http://venturebeat.com/2015/11/10/sources-classpass-raises-30-million-from-google-ventures-and-others/");

 $search_string = "Two years in,&nbsp;the company has expanded to 35 cities, five of which are outside the U.S. Plus,&nbsp;in&nbsp;April, ClassPass acquired its main competitor,&nbsp;Fitmob."; 

$replacement_string = "<span class='smth'>Two years in,&nbsp;the company has expanded to 35 cities, five of which are outside the U.S. Plus,&nbsp;in&nbsp;April, ClassPass acquired its main competitor,&nbsp;Fitmob.</span>"; 

推荐答案

这不是一种非常有效的方法,但它应该为您锻炼,

Not a very efficient way of doing it but it should workout for you,

preg_replace('Two.*?years.*?in.*?the.*?company.*?has.*?expanded.*?to.*?35.*?cities.*?five.*?of.*?which.*?are.*?outside.*?the.*?U\.S\..*?Plus.*?in.*?April.*?ClassPass.*?acquired.*?its.*?main.*?competitor.*?Fitmob\.', '<span class=\'smth\'>$0</span>', $subject);

这篇关于使用preg_match的RegEx查找和替换类似字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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