SsKacpersS
SsKacpersS

Reputation: 23

How can i get file name without extension via regex?

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 class="alignnone size-medium wp-image-18" src="http://localhost/wp-content/uploads/2015/02/300x149-jquerymobile.jpg" alt="" width="300" height="149">

Have been workin on: Regex101

Upvotes: 0

Views: 74

Answers (1)

The fourth bird
The fourth bird

Reputation: 163227

You could write the pattern like this:

(<img\b[^<>]*\bsrc="[^\s"]*/([^\s]+)\.\w+")([^<>]*\balt=")("[^<>]*>)

Regex demo

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.

Upvotes: 1

Related Questions