Home > Net >  PHP regex in preg_replace_callback
PHP regex in preg_replace_callback

Time:12-06

I use the function preg_replace_callback to find and replace text parts in a large text.

$text = 'Show me the title with tooltip for cocktail White Russian cocktail_8337. Show me the title for cocktail numbered cocktail_2. Or give me the title for cocktail_83.';
$text = preg_replace_callback('/cocktail_(?<id>\S{1})/',  

function ($matches) {
    if( is_numeric($matches[1]) ) {

        return '<span title="'.$matches[1].'">'.$matches[0].'</span>';
        
    } else {
        return ''.$matches[0].''
    }
    
}, $text );

Result should be:

... Name 8337 ... name 2 ... Name 83 ...

My problem: only the first number is taken and replaced: cocktail_8 instead of cocktail_8337. By mistake 337 is appended to the new string. I would like that really only numbers are used, from one to 10 digits.

Does anyone have an idea, please?

CodePudding user response:

If the id is numeric then the regex that you should use is '/cocktail_(?<id>\d )/'.

Note that I used instead of {1} which is what caused the first digit to be taken only(i.e. getting cocktail_8 instead of cocktail_8337) and the \S is replaced with \d because you said the id is "only numbers from one to 10 digits".

You can check that its no more than 10 digits if you need to do so by replacing the with {1,10}

CodePudding user response:

Using (?<id>\S{1}) which can also be written as (?<id>\S) and as you don't use the named group in the code, be shortened to (\S) matches a single non whitespace character.

If you want to match 1 or more digits, you can use (\d )

To do the replacement, you don't have to use preg_replace_callback and checking for is_numeric. You can just use preg_replace:

$text = 'Show me the title with tooltip for cocktail White Russian cocktail_8337. Show me the title for cocktail numbered cocktail_2. Or give me the title for cocktail_83.';
$text = preg_replace('/cocktail_(\d )/', '<span title="$1">$0</span>', $text);
echo $text;

Output

Show me the title with tooltip for cocktail White Russian <span title="8337">cocktail_8337</span>. Show me the title for cocktail numbered <span title="2">cocktail_2</span>. Or give me the title for <span title="83">cocktail_83</span>.
  • Related