Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

php - RegEx with preg_match to find and replace a SIMILAR string

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>"; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...