I need to add alt description of image when there is none via regex, but furthest I got was extracting the file name with the extension.
The problem is with extracting only file name from src of the image without any extension and put it as alt text of image.
Furthest i got within code is:
/(<img.*?)(src=")(.*?\/)([^\/]*")(.*?)(alt=")(.*?")([^>]*>)/
with example of:
<img src="http://localhost/wp-content/uploads/2015/02/300x149-jquerymobile.jpg" alt="" width="300" height="149">
Have been workin on: Regex101
CodePudding user response:
You could write the pattern like this:
(<img\b[^<>]*\bsrc="[^\s"]*/([^\s] )\.\w ")([^<>]*\balt=")("[^<>]*>)
And replace using the capture groups with:
$1$3$2$4
Note that this will only work if the src comes before the alt.
A better option is using a dom parser / DOMDocument, then get the src value and extract the image name without the extension.
Then set that to the alt value.