0

I'm building a report in PHP, and am really new to this language.

I read the documentation on preg_replace, but it's not working exactly as I expect.

Here's my code:

    $pattern = 0;
    $replacement = ' ';

    $report_output.= '
        <td>'.preg_replace($pattern, $replacement, round($row[$win_count])).'</td>
    ';

Instead of replacing a result of 0 with an empty string, it replaces all results with an empty string. The round works great like this:

    <td>'.round($row[$win_count]).'</td>

It's just when I put the preg_replace around it, it says 'phooey, I shall replace everything'. What am I doing wrong?

4
  • Try str_replace instead, you don't need regex in your case. You just want to replace all the occurence of the given string. php.net/manual/fr/function.str-replace.php Commented Sep 13, 2016 at 3:22
  • 0 is not the same as '0' Commented Sep 13, 2016 at 3:24
  • where are those delimiters at? try this '/^0$/' as your pattern. ^ is start $ is end so match only one 0 Commented Sep 13, 2016 at 3:44
  • I am new and didn't understand delimiters - I had tried delimiters previously but didn't have it right, thank you. Commented Sep 13, 2016 at 7:23

2 Answers 2

1

Try this instead

$pattern = '/^0$/';
$replacement = ' ';

$report_output.= '
    <td>'.preg_replace($pattern, $replacement, round($row[$win_count])).'</td>
';
  • The ^ means match start of string
  • The 0 is match one 0
  • The $ means match end of string

So it will only match '0' one zero start to finish and not something like this hell0 the end 0 wont be matched because the l is not the start of the string.

Your question is confusing if you want any 0 anywhere then use this instead

$pattern = '/0/';

With delimiters.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! This worked, I appreciate your guidance and apologize for being confusing. I edited my original question so hopefully it's more clear for others.
You know round has a second parameter? for the precision which is the number of decimals php.net/manual/en/function.round.php
I don't think I endorse regex for this very simple task.
@mickmackusa - I would agree with this. However I was just fixing the existing code as It was a more general error with missing the delimiters in the regex, which may help the OP more with further Regex attempts. then simply showing them how to replace the 0. In general showing 0's that are not number fields would probably be a formatting error in the data which should be null or empty
0

You can use a simple shorthand ternary.

Generally: $variable ?: ''

If it is a false value, then the fallback empty string will be used.

Code: (Demo)

printf(
    '"%s" vs "%s"',
    round($row[$win_count]),
    round($row[$win_count]) ?: ''
);

Output:

"0" vs ""

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.