Question

Im looking for a way to strip away < and > and everything in between these in PHP. And save it to a variable.

Example:

From this: <p>This is a paragraph with <strong>bold</strong> text</p>

To this: This is a paragraph with bold text

Anyone got an example or idea? Thank you!

Was it helpful?

Solution

if you do not have nested > and <, then you can try the following to match occurences:

$matches = array();
preg_match_all('/<([\s\S]*?)>/s', $string, $matches);

Try for yourserlf here. Note the ? in the query which makes the match in parentheses ungreedy. You can find an answer to a similar question here on SO.

If you want to strip away the values, then use preg_replace_callback:

<?php
$string = '&lt;p&gt;This is a paragraph with &lt;strong&gt;bold&lt;/strong&gt; text&lt;p&gt;';
echo "$string <br />";
$string = preg_replace_callback(
        '/&lt;([\s\S]*?)&gt;/s',
        function ($matches) {
            // do whatever you need with $matches here, e.g. save it somewhere
            return '';
        },
        $string
    );
echo $string;
?>

OTHER TIPS

The < encoding is html-encoding. To handle that, you want html_entity_decode() to decode or htmlentities() to encode.

Something like this:

$matches = array();
// Save
preg_match_all('!(<[^>]++>)!', $string, $matches);
// Strip
$string = strip_tags($string);

Or replace < with &lt; and > with &gt; if that was not a typo and you want to operate on already escaped string and use preg_replace('/(&lt;.+?&gt;)/', '', $string) to strip tags.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top