|
-
Jul 28th, 2003, 04:05 PM
#1
Thread Starter
Stuck in the 80s
[Resolved] preg_match() or something?
In my table, there's a bunch of text that may contain image tags, such as:
What I need to do is is search through the whole text and extract all the images and put them in an array. So the above would give me:
I've tried various things with preg_match() and preg_replace(), but I'm fumbling around.
With preg_match, it will still have the various [img] stuff in it and will be in one string, rather than an array. So there's a bunch of additional stuff I'd have to do to parse it.
Is there a better way?
Last edited by The Hobo; Jul 28th, 2003 at 06:14 PM.
-
Jul 28th, 2003, 04:32 PM
#2
Thread Starter
Stuck in the 80s
Alright. I looked at the manual and learned that the PREG_OFFSET_CAPTURE flag will place the results in an array, so I got that problem covered.
So I'm running the following code:
Code:
<?php
$body = 'Text here
[img align=left]http://www.image.com/image.gif[/img]
Text here
[img align=right]http://www.image.com/image2.gif[/img]
Text here
[img]http://www.image.com/image3.gif[/img]
Text here';
echo '<div style="width: 500px;">
<span style="font-size: 8pt;">
<b>original text</b>:
</span>
<hr>' . nl2br($body) . '<hr>';
echo '<br><span style="font-size: 8pt;"><b>the links</b>:</span><hr>';
preg_match('/\[img(.*)\](.*)\[\/img\]/i', $body, $matches, PREG_OFFSET_CAPTURE);
for ($i = 0; $i < count($matches[0]) - 1; $i++) {
echo preg_replace('/\[img(.*)\](.*)\[\/img\]/i', '\\2', $matches[0][$i]) . '<br>';
}
echo '<hr></div>';
?>
But it only seems to catch the first link?
-
Jul 28th, 2003, 04:45 PM
#3
Thread Starter
Stuck in the 80s
I suppose if I would have read the manual a little better, I would see that it says:
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject.
Whoops.
But it still doesn't return the last link?
-
Jul 28th, 2003, 06:13 PM
#4
Thread Starter
Stuck in the 80s
Holy cow. Kagey and I just wasted an hour on this...
Code:
for ($i = 0; $i < count($matches[0]) - 1; $i++) {
echo preg_replace('/\[img(.*)\](.*)\[\/img\]/i', '\\2', $matches[0][$i]) . '<br>';
}
I was skipping the last match. All that time and I thought it was messed up pattern syntax.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|