1

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 ...

Francis Laclé
  • 384
  • 2
  • 6
  • 22
  • 1
    http://tinyurl.com/cm8ea5 please post the code of what you have already tried if you need a quicker response from the community. – Aditya M P Mar 04 '11 at 15:01
  • Just to note, title and alt are attributes, not tags. And technically image tags don't require a title attribute as the alt attribute is used by screen readers and when images are disabled to show a description of the image, but that's way not the point :-) – Alex Mar 04 '11 at 15:05
  • possible duplicate of [RegEx match open tags except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – RobertPitt Mar 04 '11 at 15:09

5 Answers5

2

Rather than a regex, have a look into PHP DOMDocument to modify attributes, especially if there will be any complexity.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
2

You could use phpQuery or QueryPath 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.)

mario
  • 144,265
  • 20
  • 237
  • 291
0

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

markijbema
  • 3,985
  • 20
  • 32
0

My answer is a link to a well known answer!

RegEx match open tags except XHTML self-contained tags

Community
  • 1
  • 1
RobertPitt
  • 56,863
  • 21
  • 114
  • 161
0

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);
John Himmelman
  • 21,504
  • 22
  • 65
  • 80