我在preg_replace()
中使用正则表达式,以便查找并替换一段文本中的句子。 $search_string
包含纯文本+ html标记+
元素。问题在于,只有
元素有时会在运行时转换为空白,这使得使用str_replace()
进行查找和替换变得困难。因此,我正在尝试构建一个与搜索字符串相等的模式,并将匹配包含或不包含
元素的任何内容;
例如:
$search_string = 'Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, <a href="site.com">ClassPass</a> acquired its main competitor, Fitmob.';
[$pattern
= $search_string
(但忽略主题中的
元素)]
$subject = "text text text text text". $search_string . "text text text text text";
使用A regular expression to exclude a word/string,我已经尝试过:
$pattern = '`^/(?!\ )'.$search_string.'`';
$output = preg_replace($pattern, $replacement_string,$subject);
最终结果是,如果$ subject确实包含一个类似于我的$seach_string
的字符串,但没有
元素,它将仍然匹配并替换为$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, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, ClassPass acquired its main competitor, Fitmob.";
$replacement_string = "<span class='smth'>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>";
不是一种非常有效的方法,但是它应该为您锻炼,
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);