79258

PHP preg match / replace?

Question:

I need to read the string $mysting and replace all incident of e.x.

<img src="dummypic.jpg alt="dummy pic">

with

<img src="dummypic.jpg alt="dummy pic" title="dummy pic">

in other words add the title where it is missing, and make the title tag have the same value as the alt tag.

some incident my have additional parameters like border, with, height - and these should be left untouched ...

Answer1:

Rather than a regex, have a look into <a href="http://php.net/manual/en/class.domdocument.php" rel="nofollow">PHP DOMDocument</a> to modify attributes, especially if there will be any complexity.

Answer2:

You could use phpQuery or <a href="http://querypath.org/" rel="nofollow">QueryPath</a> to do that:

$qp = qp($html); foreach ($qp->find("img") as $img) { $img->attr("title", $img->attr("alt")); } print $qp->writeHTML();

Though it might be feasible in this simple case to resort to an regex:

preg_replace('#(<img\s[^>]*)(\balt=)("[^"]+")#', '$1$2$3 title=$3', $h);

(It would make more sense to use preg_replace_callback to ensure no title= attribute is present yet.)

Answer3:

You really want to do this using an html parser instead of regexes. Regexes are not suited for html processing.

Answer4:

My answer is a link to a well known answer!

<a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454" rel="nofollow">RegEx match open tags except XHTML self-contained tags</a>

Answer5:

I usually write quick dirty hacks in these types of situations (usually working with structured data, that might have inconsistencies such as templating engine tags, conditionals, etc.). IMO its a terrible solution, but I can bang out these scripts super fast.

Eg.

<? $html = ' <img src="dummypic.jpg" alt="dummy pic"> <img src="dummypic2.jpg" alt="dummy pic 2"> blahaahhh <img src="dummypic.jpg" alt="dummy pic"> <img src="dummypic2.jpg" alt="dummy pic 2"> '; $tags = explode('<img', $html); for ($i = 1; $i < count($tags); $i++) { $src = explode('src="', $tags[$i]); $src = explode('"', $src[1]); $src = str_replace('.jpg', '', $src[0]); $tags[$i] = '<img title="' . $src . '"' . $tags[$i]; } echo implode('', $tags);

Recommend

  • Escaping of rails-generated URL
  • How to create a field class containing an image in Ext JS 4?
  • draw multiple encoded polylines using api v3
  • What's the difference with crf and qp in ffmpeg?
  • Time Complexity of the given nested loops
  • Dynamic programming matrix chain multiplication
  • How to get an estimated amount of talktime,music/video playback time, idletime that could be possibl
  • Entity Framework Code First Circular Dependices
  • Why the time complexity of an array insertion is O(n) and not O(n+1)? [duplicate]
  • .NET Obfuscation [SmartAssembly]
  • Angular 2.0 routing - TS 2305 … has no exported member 'ModulewithProviders'
  • Parsing tokens with PLY
  • Using Regex to split XML string before and after match
  • Regex: Match everything except backreference
  • pandas parse csv with left and right quote chars
  • How do I distinguish jQuery selector strings from other strings
  • php regex remove digits
  • r - extract alphanumeric strings from text
  • Zend Framework 2 - Building a simple form with Validators
  • Use Variable in Regular Expression in javascript
  • Replace HTML links with text
  • Get XML response value with GDataXML
  • Why isn't \\\\ interpreted as a blackslash in this regex?
  • C++ and JS RegEx equivalent of \\p{L}
  • CSS Grid, position absolute an element in a css grid item: IMPOSSIBLE
  • Scala using regex with or syntax in match case statement
  • Negating Regex PO BOX
  • Efficient User-Agent Regex to find Safari in Python
  • how to get data attributes of dynamically generated element
  • ListItem.Attributes.Add not working
  • OOP Javascript - Is “get property” method necessary?
  • How to change the font size of a single index for UISegmentedControl?
  • Disable Enter in editText android
  • Extracting HTML between tags
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Master page gives error
  • Regex thinks I'm nesting, but I'm not
  • How to check if every primary key value is being referenced as foreign key in another table
  • Redux, normalised entities and lodash merge
  • python regex in pyparsing