0

I'm trying to replace image names within a page by using preg_replace but I'm probably missing something with regular expressions.

For the sake of the example, I'll use the following page: https://www.laurentwillen.be/circuits/circuit-autriche/alpbach/

So here is what I do:

$media = get_attached_media( 'image', $metadata["page_id"] );
foreach ($media as $key=>$value)
{
    $old_image = explode("/",$media[$key]->guid);
    $old_image = $old_image[sizeof($old_image)-1];
    $old_image = explode(".",$old_image);
    $old_image = "/".$old_image[0]."/";
    $new_image = wp_get_attachment_image_src($key,'tablet');
    $new_image = explode ("/",$new_image[0]);
    $new_image = $new_image[sizeof($new_image)-1];
    $new_image = explode (".",$new_image);
    $new_image = "/".$new_image[0]."/";
    preg_replace($old_image,$new_image,$content,-1,$count);
}

To spare you the trouble of guessing the variable values, here is what $old_image and $new_image represent for the page given higher:

$old_image values:

/alpbach-photo-1/
/alpbach-photo-2/
/alpbach-photo-3/
/alpbach-photo-4/
/alpbach-photo-5/
/alpbach-photo-6/
/alpbach-photo-top/

$new_image values:

alpbach-photo-1-900x600
alpbach-photo-2-900x600
alpbach-photo-3-900x600
alpbach-photo-4-900x600
alpbach-photo-5-900x600
alpbach-photo-6-900x600
alpbach-photo-top-900x281

The count for preg_replace returns

9
0
9
0
9
0
0

But in the end, nothing is replaced.

If I try manually this:

preg_replace("/alpbach-photo-3/","/alpbach-photo-1/",$content,-1,$count);

Nothing is replaced either.

What am I doing wrong? Any idea?

Thanks!

1 Answer 1

1

As php manual says:

preg_replace() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

So you need to store the result of preg_replace into some variable.

$result = preg_replace($old_image,$new_image,$content,-1,$count);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but the subject is not an array, it's a string containing the whole page. If I store the result in a variable, the variable outputs the content with no change. You can check on the example page, in the source code, look for DEBUG, you'll see the output of $content where nothing has been replaced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.