user1902427
user1902427

Reputation: 73

Wrap a number followed by a percent symbol in <b> tags

I have some text (in this specific case $expression), sometimes it is quite long. I want to output the text the same way it is, except outputting numbers % bold. Sometimes its spelled like 3% and sometimes there's a space like 123 %.

<?php
$expression = 'here we got a number 23 % and so on';
$tokens = "([0-9]+)[:space:]([\%])";
$pattern = '/[0-9][0-9] %/';

$keyword = array($pattern);
$replacement = array("<b>$keyword</b>");
echo preg_replace($keyword, $replacement, $expression);
?>

This is what I have but I'm not exactly sure what I'm doing wrong. It outputs an error on the line $replacement = array("<b>$keyword</b>"); and then outputs the actual string except it replaces the number% with <b>Array</b>.

Upvotes: 2

Views: 114

Answers (4)

mickmackusa
mickmackusa

Reputation: 47864

No single answer has all of the best practices baked into a scripted implementation. The pattern needs to match one or more digits, followed by an optional space, followed by a literal percent symbol.

The replacement can be wrapped in single quotes and backreference the fullstring match (there is no need for any capture groups because the fullstring is enough).

Code: (Demo)

$expression = 'here we got a number 23 % and so on';
echo preg_replace(
         '/\d+\s?%/',
         '<b>$0</b>',
         $expression
     );
// here we got a number <b>23 %</b> and so on

Upvotes: 0

Daniel Gomes
Daniel Gomes

Reputation: 629

Your pattern and replacement are wrong, you need a group in the pattern in order to have a "variable" placeholder in the replacement. Check the preg_replace manual for more details.

I created this gist with a solution, the code on it:

<?php

$expression = 'here we got a number 23 % and so on';
$pattern = '/(\d+ %)/';
$replacement = '<b>$1</b>';
echo preg_replace($pattern, $replacement, $expression);

Upvotes: 0

Ejaz
Ejaz

Reputation: 8872

try this

$expression = 'here we got a number 23 % and so on';
var_dump(preg_replace('/(\d+\s*\%)/', "<b>$1</b>", $expression));

Upvotes: 2

hakre
hakre

Reputation: 197659

You face an (unwanted) array to string conversion. In development always make the warnings/notices visible, PHP tells you that this happens (and where).

Also look again on the preg_replace manual page, it shows the correct syntax for the replacement. Follow especially the part about backreferences in the replacement parameter.

$replacement = array("<b>\\0</b>");

Upvotes: 2

Related Questions