Reputation: 815
I have a description field with user entering {tag}This has to be replaced{/tag}
I want to replace the text with another. For this I am using the following code:
<?php
$find = "/[^{tag}](.*)[^{\/tag}]/";
$string = '{tag}This has to be replaced {/tag}';
echo preg_replace($find, 'new text',$string);
?>
But I am not getting desired result. Also, in output I only want: new text
. I don't want like this: {tag}New text{/tag}
Apart from this, how can I get the text between these tags ?
Kindly guide me on this
Upvotes: 2
Views: 2897
Reputation: 174696
Use a non-greedy regex..
$find = '~{tag}.*?{/tag}~';
echo preg_replace($find, 'new text',$string);
If the text between tag
/tag
contain newline characters then you must use DOTALL modifier.
$find = '~(?s){tag}.*?{/tag}~';
To get text between those tags, use capturing groups/.
$find = '~{tag}(.*?){/tag}~';
$out = preg_match($find, $str);
echo $out[1];
Upvotes: 3