Cris Kolkman Cris Kolkman - 2 months ago 7
PHP Question

Remove everything BEFORE and AFTER certain chars in a string

Good day,

I want to remove everything before and after a certain character sequence in a string.

E.g:

$string = 'TESTING<html>This is a string</html>ANOTHER TEST!!';


I want everything before
<html>
and after
</html>
to be removed, so that the string looks like this when I write it to a database:

<html>This is a string</html>


Important thing here is that
<html>
and
</html>
keep existing in the string.

Anyone got an idea?

Answer Source

Try something like this:

// vars
$string = ' This is text before <html> and this is the text in between </html> And after there is some more text.. ';
$first = '<html>';
$last = '</html>';
// job
$start = stripos($string, $first); // first occurrence position 
$length = strripos($string, $last); // last occurrence position 
$newString = substr($string, $start, ($length-$start+strlen($last))); 
// output
var_dump($string,$start,$length,$newString);