0

$string = "Lorem Ipsum is #simply# dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard #dummy# text ever since the 1500s, when an unknown printer took a galley of #type1# and scrambled it to #make# a #type2# specimen book. It has survived not only #five# centuries, but also the #leap# into electronic typesetting, remaining essentially unchanged";

I have set of hard code words like "#simply# | #dummy# | #five# | #type1#"

What I expect as a output is:

  1. If hard code words is found in $string it should get highlighted in black. like "<strong>...</strong>".

  2. If a word in $string is within #...# but not available in the hard code word list then those words in the string should get highlighted in red.

  3. please note that even though we have #type1# in hard code words, if $string contains #type2# or #type3# it should also get highlighted .

for doing this I have tried as below

$pattern = "/#(\w+)#/";

$replacement = '<strong>$1</strong>';

$new_string = preg_replace($pattern, $replacement, $string);

This gets me all the words which are within #..# tags highlighted.

I'm bad in preg_ can someone help. thanks in advance.

2 Answers 2

1

You have to use preg_replace_callback that takes a callback function as replacement parameter. In the function you can test which capture group has succeeded and return the string according to.

$pattern = '~#(?:(simply|dummy|five|type[123])|(\w+))#~';
$replacement = function ($match) {
    if ( empty($match[2]) )
        return '<strong>' . $match[1] . '</strong>';
    else
        return '<strong style="color:red">' . $match[2] . '</strong>';
};

$result = preg_replace_callback($pattern, $replacement, $text);
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure I really understand your needs, but what about:

$pat = '#(simply|dummy|five|type\d)#';
$repl = '<strong>$1</strong>';
$new_str = preg_replace("/$pat/", $repl, $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.