Home » Php » regex – How can I echo PHP within a preg_replace?

regex – How can I echo PHP within a preg_replace?

Posted by: admin February 25, 2020 Leave a comment

Questions:

OK, I’ve been trying to figure this out for 3 days, but I can’t seem to get the code right.

The following code displays my title:

<?php echo $result['title'];?>

The following code displays my content:

<?php
if(!empty($result['content']))
{
$result['content'] = str_replace(array("\n"), "<br/><br/>", $result['content']);
echo preg_replace('#(<br */?>\s*)+#i', '<br/><br/>', $result['content']);
}
?>

Within the preg_replace, I need to echo the title between the 2 br tags; something like this:

<?php
if(!empty($result['content']))
{
$result['content'] = str_replace(array("\n"), "<br/><br/>", $result['content']);
echo preg_replace('#(<br */?>\s*)+#i', '<br/>$result['title']<br/>', $result['content']);
}
?>

Thank you in advance for the much-needed help!

How to&Answers:

You are using string literals here that will result in error: '<br/>$result['title']<br/>', you can alternatively concat. or do something like this: "<br/>{$result['title']}<br/>".

<?php
$result['title']   = 'Weather warning.';
$result['content'] = 'Today sees high gusts.
You are advised to not make unnecessary journeys.';

if(!empty($result['content']))
{
    $result['content'] = str_replace(array("\n"), "<br/><br/>", $result['content']);
    echo preg_replace('#(<br */?>\s*)+#i', "<br/>{$result['title']}<br/>", $result['content']);
}

Output:

Today sees high gusts.<br/>Weather warning.<br/>You are advised to not make unnecessary journeys.

Though my example text reads nonsensically.