Reputation: 165
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?
Upvotes: 3
Views: 358
Reputation: 191
Along with the posted answers, you can also use strstr()
function to get the text before and after like;
$newstring = '<html>' . strstr($string, '<html>');
$newstring = strstr($newstring, '</html>', true) . '</html>';
Upvotes: 0
Reputation: 1684
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);
Upvotes: 3
Reputation: 1878
Can be done with a regular expression:
$str = 'TESTING<html>This is a string</html>ANOTHER TEST!!';
preg_match_all('/(<html>.*<\/html>)/', $str, $matches);
print_r($matches[1][0]);
For a multiline string, you have to add the modifier "m":
$str = 'TESTING<html>This is a string</html>ANOTHER TEST!!';
preg_match_all('/(<html>.*<\/html>)/m', $str, $matches);
print_r($matches[1][0]);
Upvotes: 5