Question

From a variable, I want to remove double square brackets [[ ]] and everything in between, and then replace it with img inserted

I've got the following column result:

<p>hey</p><p>[[{"type":"media","view_mode":"media_large","fid":"67","attributes":{"alt":"","class":"media-image","height":"125","typeof":"foaf:Image","width":"125"}}]]</p>

After replace the variable should become:

<p>heey</p><p><b>img inserted<b></p>

I've tried to use preg_replace but this seems to be too advanced for me yet..

Can anyone give me some advice on how to achieve this?

Was it helpful?

Solution

$string = '<p>hey</p><p>[[{"type":"media","view_mode":"media_large","fid":"67","attributes":{"alt":"","class":"media-image","height":"125","typeof":"foaf:Image","width":"125"}}]]</p>';
$new_string = preg_replace('/\[\[.*?\]\]/', '<b>img inserted</b>', $string);

echo $new_string;

OTHER TIPS

Try this:

<?PHP
    $subject = '<p>hey</p><p>[[{\"type\":\"media\",\"view_mode\":\"media_large\",\"fid\":\"67\",\"attributes\":{\"alt\":\"\",\"class\":\"media-image\",\"height\":\"125\",\"typeof\":\"foaf:Image\",\"width\":\"125\"}}]]</p>';
    $pattern = '/\[\[[^[]*]]/';
    $replace = '<b>img inserted</b>';
    $result = preg_replace($pattern, $replace, $subject);
    echo '<p>Result: '.htmlspecialchars($result).'</p>';
?> 

For your explanation: /.../ delimits the regular expression. The [[ has to be escaped, because [ is a special character, thus \[\[. After that, we get any character that is not a [ by using [^[]. This is repeated as often as needed: [^[]*. After that, we have two brackets: \]\]

Also, this will not work if within the square brackets there is a [. Judging from your format, this is not the case. Otherwise, you would have to use a more complicated syntax, most likely using back-references if those extra ['s are escaped ([). If unescaped brackets can occur, you cannot solve this with regular expressions.

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