Forum Moderators: coopster

Message Too Old, No Replies

preg match help

         

Sandro87

1:05 pm on Feb 7, 2010 (gmt 0)

10+ Year Member



Hello
I'm trying to do something after the preg_match condition if in the content there are images (<img />) with

preg_match('/<img[^>]+>/i',$content)

this works. But my goal is to do something only of those images ARE NOT linked (<a><img /></a>), if they are return 0.

I'm sure it's simple but I can't seem to solve it :)

[edited by: eelixduppy at 3:37 pm (utc) on Feb 7, 2010]
[edit reason] disabled smileys [/edit]

rocknbil

8:01 pm on Feb 7, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



... if in the content there are images (<img />)


first, you specify XHTML style matches but don't include it in the preg. This should have worked, but just in case, zero or more on the space and /.


if (preg_match('/<img[^>]+\s*\/*>/i',$content)) {
//
}

That will capture both <img> and <img /> (although, you're probably not doing and extending, but anyway . . . )

But my goal is to do something only of those images ARE NOT linked (<a><img /></a>)


But you didn't show what you tried. :-)


if (preg_match('/<img[^>]+\s*\/*>/i',$content)) {
if (! preg_match('/<a[^>]+>\s*<img[^>]+\s*\/*>\s*<\/a>/i',$content)) {
return 0;
}
}


There's a problem with this though, thinking forward.

It's evaluating the whole block, so you will have difficulty in pointing out exactly what the problem is to the end user. Nothing more frustrating than blurting out a huge block of text then getting "somewhere in your tome is a problem." I'd probably do something like parse it line by line, and in combination . . .

if you use a preg replace in this little scriptlet, you can address the above, but you'll have to return the modified block of text. An example might be:


// or use $line parsing it line by line
list($err,$newtext)=check_content($orig_content);
//
if ($err) { return_to_form($err,$newtext); }
//
function check_content($content) {
$error=NULL;
// This should actually be a setting.
$span = '<span style="color:red;font-weight:bold">';
$span_close = '</span>';
if (preg_match('/<img[^>]+\s*\/*>/i',$content)) {
if (! preg_match('/<a[^>]+>\s*<img[^>]+\s*\/*>\s*<\/a>/i',$content)) {
$content = htmlentities(preg_replace('/(<img[^>]+\s*\/*>)/i',"$span$1$close_span",$content));
}
}
$ret = Array($error,$content);
return $ret;
}


Untested, may have bugs, but that's the idea, anyway.

[edited by: eelixduppy at 2:27 am (utc) on Feb 9, 2010]
[edit reason] disabled smileys [/edit]

Sandro87

11:51 pm on Feb 8, 2010 (gmt 0)

10+ Year Member



/<a[^>]+>\s*<img[^>]+\s*\/*>\s*<\/a>/i

that's what I needed, thanks