GOOG
GOOG

Reputation: 73

preg_match and preg_replace in string php

$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.

Upvotes: 0

Views: 879

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89566

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);

Upvotes: 1

Toto
Toto

Reputation: 91428

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);

Upvotes: 0

Related Questions