Shiromi
Shiromi

Reputation: 157

How to replace a hashtag followed by a number?

I want to replace as FALSE where the string contains a # followed by an integer.

This is my code:

$newlogicexpression = '#1 and (1743327.12 >  10)';
if( strpos( $newlogicexpression, '#' ) !== false ) {
    $newlogicexpression = str_replace('#', 'FALSE', $newlogicexpression);
    $this->logger->debug($newlogicexpression);
}

My expected result is: FALSE and (1743327.12 > 10)

My current output is: FALSE1 and (1743327.12 > 10)

Based on the post method, the integer that follows the # may differ.

The replacement need to happen at any position in the string.

Upvotes: 0

Views: 392

Answers (2)

mickmackusa
mickmackusa

Reputation: 48100

There is only one sensible way to do this -- with preg_replace () -- and you don't need the condition check. If a number is preceded by a hashtag symbol, the replacement will be made (multiple times if possible). If the pattern matches nothing, then the input string remains unchanged.

In the pattern, I am using tildes for pattern delimiters. The # doesn't need to be escaped to be intrepreted literally. \d means any digit character (0 to 9). The + means one or more occurrences of any digit.

Effectively, the following substrings would be replaced: #1, #3098426893219, and #04. Matches can be found anywhere in the string.

Code: (Demo)

$newlogicexpression = '#1 and (1743327.12 >  10)';
echo preg_replace('~#\d+~', 'FALSE', $newlogicexpression);

Output:

FALSE  and (1743327.12 >  10)

Update on 2018-12-08:

I'm not entirely sure why I lost an upvote today with no explanation, but if you only want to call $this->logger->debug($newlogicexpression); when there is a replacement made, you can use this (still only one function call):

$newlogicexpression = '#1 and (1743327.12 >  10)';
$newlogicexpression = preg_replace('~#\d+~', 'FALSE', $newlogicexpression, 1, $count);  // only 1 replace permitted, otherwise use -1
if ($count) {
    $this->logger->debug($newlogicexpression);
}

Upvotes: 0

user70960
user70960

Reputation: 326

There are many ways to do that.
For example, you can use this regular expression: #\d+

Therefore:

$newlogicexpression = '#1 and (1743327.12 >  10) and #2';
if( strpos( $newlogicexpression, '#' ) !== false ) {

    $newlogicexpression = preg_replace('/#\d+/', 'FALSE', $newlogicexpression);
    $this->logger->debug($newlogicexpression);

}

Upvotes: 3

Related Questions