Reputation: 1629
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?
Upvotes: 1
Views: 2493
Reputation: 8343
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.
Upvotes: 3
Reputation:
$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;
Upvotes: 3