如何查找带有 php 的字符串?

How to find a string with php?

我有一个字符串:"Tip #123 some random text" 并且我需要在 #123 之后放置一个 <br /> 标记,以便 some random text 位于一个新行中。

我可以用 strpos 找到 #,但是我从那里去哪里呢?

您可以使用以下代码:

/**
 * Function to create a dynamic replacement.
 * @param array $match An array with the match of the pattern.
 * @return string The replacement.
 */
function getReplacement($match)
{
    if (isset($match[0])) {
        return $match[0].'<br/>';
    }
}

//the value to replace specific parts.
$string = 'Tip #1 some #12 random #123 text #1234, an #12345 example #123456';

//replace all parts starting with '#' and three numbers following.
echo preg_replace_callback('/#[0-9]+/', 'getReplacement', $string);

您可以在此处找到一个工作示例:https://3v4l.org/RNmkj