PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How can i get file name without extension via regex?

 November 19, 2022     php, preg-replace, regex     No comments   

Issue

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


Solution

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.



Answered By - The fourth bird
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing