0

I have a string: "Tip #123 some random text" and I need to place a <br /> tag after #123 so that some random text is in a new line.

I could find the # with strpos, but where do I go from there?

Xeen
  • 6,955
  • 16
  • 60
  • 111
  • Take a look at `str_replace()`. Just `#123` to `#123
    `
    – Rizier123 Mar 15 '16 at 14:01
  • @Rizier123 ok, but what if the string is `#126`, I need to find the full number and how can I do that? So the `#` + following numbers form a string I must find. – Xeen Mar 15 '16 at 14:03
  • 1
    Then you want to use `preg_replace()`. And say that you want `#\d+` instead of hardcoded `#123` – Rizier123 Mar 15 '16 at 14:04
  • Possible duplicate of [Check if string contains specific words?](http://stackoverflow.com/questions/4366730/check-if-string-contains-specific-words) – Tomasz Ferfecki Mar 15 '16 at 14:06
  • http://stackoverflow.com/questions/2681786/how-to-get-the-last-char-of-a-string-in-php – Hamza Zafeer Mar 15 '16 at 14:07

1 Answers1

2

You can use the following code:

/**
 * 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);

A working example you can find here: https://3v4l.org/RNmkj

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87