PHP string replace question
If I have a string that equals "firstpart".$unknown_var."secondpart", how can I delete everything between "firstpart" and "secondpart" (on a page that does not know the value of $unknown_var)?
开发者_C百科Thanks.
Neel
substr_replace
start and length can be computed with strpos. Or you could go the regex route if you're comfortable learning about them.
As long as $unkonwn_var
does not contain neither firstpart
nor secondpart,
you can match against
firstpart(.*)secondpart
and replace it with
firstpartsecondpart
You shoukd use a regexp to do so.
preg_replace('/firspart(.*)secondpart/','firstpartsecondpart',$yourstring);
will replace anything between the first occurence of firstpart and the last of secondpart, if you want to delete multiple time between first and second part you can make the expression ungreedy by replacing (.*)
by (.*?)
in the expression
preg_replace('/firspart(.*?)secondpart/','firstpartsecondpart',$yourstring);
精彩评论