3

I'm trying to replace the contents between some "special" characters, in each of their occurrences. For example, let's say i have that string:

<div><small>static content</small><small>[special content type 3]</small> 
<small>static content</small><small>[special content type 4]</small></div>

I would like to replace each "special content", between square brackets, with something that is represented by this "identifier"(let's say, some "widget").

I've tried this code from Stackoverflow:

$search = "/[^<tag>](.*)[^<\/tag>]/";
$replace = "your new inner text";
$string = "<tag>i dont know what is here</tag>";
echo preg_replace($search,$replace,$string);

This works, but only for the first occurrence. I need this operation to be repeated across the entire string.

I've also tried this one:

echo preg_replace('/<div class="username">.+?</div>/im', '<div 
class="username">Special Username<\/div>', $string) ;

It gives me a "Warning: preg_replace(): Unknown modifier 'd' in Standard input code on line 8" error.

Any ideas?

4

2 Answers 2

2

Your code from stackoverflow needs minor changes:

$search = "/(<tag>)(.*?)(<\/tag>)/";
$replace = '$1your new inner text$3';
$string = "<tag>i dont know what is here</tag> some text <tag>here's another one</tag>";
echo preg_replace($search,$replace,$string);
Sign up to request clarification or add additional context in comments.

4 Comments

Any idea why this $search = "/([PAID_JOB])(.*?)([\/PAID_JOB])/"; doesnt work?
@Ingus you need to escape the [ and ] as they are special characters for regex.
That doesnt seems to be working $search = "/(\[tag\])(.*?)(\[\/tag\])/";
@Ingus if you are having problems, ask a question. Comments are not the place for this.
2
function replace_all_text_between($str, $start, $end, $replacement) {

    $replacement = $start . $replacement . $end;

    $start = preg_quote($start, '/');
    $end = preg_quote($end, '/');
    $regex = "/({$start})(.*?)({$end})/";

    return preg_replace($regex,$replacement,$str);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.