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?
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
` – Rizier123 Mar 15 '16 at 14:01