Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace with two replacments

Tags:

regex

php

I have a sentence in the DB for example:

His $name$ is $Luis$

Now, I want to replace the $..$ in tags (< b >), for something like:

His <b>name</b> is <b>Luis</b>

How can I do it with preg_replace? I tried to do simply:

$replace[0] = '<b>';
$replace[1] = '</b>';
preg_replace('/[$]/', $replace, $string);

But doesn't work.

like image 218
Luis Avatar asked Mar 29 '26 17:03

Luis


2 Answers

preg_replace( '/\$(.*?)\$/', '<b>\1</b>', $string );
like image 161
nobody Avatar answered Apr 01 '26 08:04

nobody


This will solve your problem:

$source = 'His $name$ is $Luis$';
$result = preg_replace('/\$(.*?)\$/', '<b>$1</b>', $source);
like image 33
scube Avatar answered Apr 01 '26 06:04

scube



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!