使用preg_match进行RegEx查找和替换SIMILAR字符串

时间:2015-11-12 12:33:27

标签: php mysql regex pattern-matching preg-replace

我正在使用preg_replace()的正则表达式来查找和替换一段文本中的句子。 $search_string包含纯文本+ html标记+  元素。问题是有时只有 元素在运行时转换为空格,因此很难使用str_replace()查找和替换。因此,我尝试构建一个与搜索字符串相同的模式,并匹配包含或不包含 元素的任何内容;

例如:

$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;元素)

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

使用A regular expression to exclude a word/string,我尝试过:

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

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

修改

实际值:

$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>"; 

1 个答案:

答案 0 :(得分:0)

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

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);