如何替换后跟数字的主题标签?

How to replace a hashtag followed by a number?

我想替换为 FALSE,其中字符串包含一个 # 后跟一个整数。

这是我的代码:

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

我的预期结果是:FALSE and (1743327.12 > 10)

我当前的输出是:FALSE1 and (1743327.12 > 10)

基于post方法,#后面的整数可能不同。

替换需要发生在字符串中的任何位置。

有很多方法可以做到这一点。
例如,您可以使用此正则表达式:#\d+

因此:

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

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

}

只有一种明智的方法可以做到这一点——preg_replace ()——而且你不需要条件检查。如果一个数字前面有一个标签符号,将进行替换(如果可能多次)。如果模式不匹配,则输入字符串保持不变。

在模式中,我使用波浪号作为模式分隔符。 # 无需转义即可按字面解释。 \d 表示任何数字字符(0 到 9)。 + 表示任意数字出现一次或多次。

实际上,将替换以下子字符串:#1#3098426893219#04。可以在字符串中的任何位置找到匹配项。

代码:(Demo)

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

输出:

FALSE  and (1743327.12 >  10)

2018-12-08更新:

我不完全确定为什么我今天没有解释就失去了一个赞成票,但是如果你只想在有替换时调用 $this->logger->debug($newlogicexpression);,你可以使用这个(仍然只有一个函数调用):

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