Neel
Neel

Reputation: 595

Remove unknown string between two known strings

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

Upvotes: 0

Views: 147

Answers (3)

malko
malko

Reputation: 2382

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

Upvotes: 0

Hyperboreus
Hyperboreus

Reputation: 32449

As long as $unkonwn_var does not contain neither firstpart nor secondpart, you can match against

firstpart(.*)secondpart

and replace it with

firstpartsecondpart

Upvotes: 1

colithium
colithium

Reputation: 10327

substr_replace

start and length can be computed with strpos. Or you could go the regex route if you're comfortable learning about them.

Upvotes: 2

Related Questions