RegEx with preg_match to find and replace a SIMILAR string

倾然丶 夕夏残阳落幕 提交于 2019-12-17 21:13:32

问题


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;

For example:

$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(BUT IGNORE THE &nbsp; elements in the subject)

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

Using A regular expression to exclude a word/string, I've tried:

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

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

EDIT:

The actual values:

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

来源:https://stackoverflow.com/questions/33671497/regex-with-preg-match-to-find-and-replace-a-similar-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!