0

i am trying to use preg_replace on a url to an image in HTML format, and turn it into BBCode.

From: <img src="http://website.com/char/sign/Name+Surname.png">

To: [sign]Name+Surname[/sign]

Note: the filename of the png file can be just Name, it can contain a middle name like: Name+Middlename+Surname, it can also contain - and %2527 like Carl-Philips or Bob+Mc%2527Donalds

So this is what I've tried so far, but it's not doing anything. What am I doing wrong?

$source = array(
    '#\<img src=\"http\:\/\/website.com\/char\/sign\/\>(.+).png\>#isU'
);

$new = array(
    '[sign]$1[/sign]'
);

$text = preg_replace($source, $new, $text);
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
holzmaster
  • 13
  • 5

1 Answers1

1

You should use a parser (How do you parse and process HTML/XML in PHP?) for these in the future. You have a few typos in your regex.

This should accomplish what you are after:

/<img src="http:\/\/website\.com\/char\/sign\/(.+?)\.png">/

Demo (with exmplanation of regex): https://regex101.com/r/sT6aG9/1

PHP Example:

$source = '/<img src="http:\/\/website\.com\/char\/sign\/(.+?)\.png">/';
$new = '[sign]$1[/sign]';
$text = '<img src="http://website.com/char/sign/Name+Surname.png">, <img src="http://website.com/char/sign/Bob-Robinson.png">, <img src="http://website.com/char/sign/Michael%2527Ross.png">';
$text = preg_replace($source, $new, $text);
echo $text;

Output:

[sign]Name+Surname[/sign], [sign]Bob-Robinson[/sign], [sign]Michael%2527Ross[/sign]

PHP Demo: http://3v4l.org/WC5oJ

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51