带有preg_match的RegEx以查找和替换相似字符串

问题描述 投票:1回答:1

我在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

编辑:

实际值:

$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>"; 
php mysql regex pattern-matching preg-replace
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.