Question

I'm working on creating a bulletin board converter. I need PHP to replace/restructure the following from:

[img alt="" src="IMAGE LINK, NOT ENDING IN AN IMAGE FORMAT EXTENSION" style="max-width:100%;"]

To:

[img]IMAGE LINK[/img]

Where everything else such as the alt tags can be deleted.

At the moment I have PHP use preg_replace (in an array) and I am using regex to try and obtain the link. However I'm struggling on finding a way to convert it over, as I've not used regex before.

Apologies for the hassle, and thank you very much! :)

Was it helpful?

Solution

I guess you will need something like this

<?php
$string = '[img alt="" src="IMAGE LINK, NOT ENDING IN AN IMAGE FORMAT EXTENSION" style="max-width:100%;"]';

$matches = array();
print preg_replace('|\[img.*src="(.*)" style.*]|', '[img]$1[/img]', $string);

prints

[img]IMAGE LINK, NOT ENDING IN AN IMAGE FORMAT EXTENSION[/img]

OTHER TIPS

For your regex this is cleaner

\[img[^\]]+?src="([^"]*)"[^\]]*\]

Replacement is the same you had.

You need the ? for laziness otherwise you will have unexpected matches For instance the first answer regex matches [img src="img1" style] [img 2] [img 3] not what you want

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top