Question

Possible Duplicate:
How to parse and process HTML with PHP?

Here is what I'm trying to do:

1.)Find all images from my wordpress blog posts

2.)Create links to their image URLs at the top of the post

3.)Give each of these links the attribute:

rel="prettyPhoto[ INSERT POST TITLE HERE ]"

Below is what I have so far:

$szPostContent = $post->post_content;
$szSearchPattern = '@src="([^"]+)"@';

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );


// Check to see if we have at least 1 image src
$iNumberOfPics = count($aPics[0]);


if ( $iNumberOfPics > 0 ) {

///this is what I want to do
/// $aPicsTRIMMED = preg_replace('/src=/','/http=/',$aPics);

 for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
echo ' <a rel="prettyPhoto['.$portTit.']"';
      echo $aPics[0][$i];
echo '>Image</a>';

     };
};

Right now, as is, this code gets me the following:

<a rel="prettyPhoto[Correct Post Title]" src="http://mydomain.com/myimage.jpg">Image</a>

very close but I need href instead of src. If you see commented out at the bottom I've been trying to use preg replace (incorrectly) and not sure if this is moving in the right direction or not. This is my first go at PHP and I've hit a wall. Hopefully someone more familiar will be able to figure this out before I can... (will post success story if I make it there) In the mean time PLEASE HELP before I drive myself crazy.

Thank you

Was it helpful?

Solution

Replace:

echo $aPics[0][$i];

With:

echo str_replace('src=', 'href=', $aPics[0][$i]);

OTHER TIPS

You are injecting the whole match src=... with this line:

      echo $aPics[0][$i];

But you only should be using the inner match group ([^"]+) from ye regex. That one is available in [1] of the match result array:

      echo ' href="' . $aPics[1][$i] . '"';

And it just needs to be surrounded by the new attribute snippets href="...".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top