0

I am adding function to replace content on the fly for every width="*" with width="730px" and every height="*"with height="846"

function replace_content_on_the_fly($text){
    $replace = array(
        // 'words to find' => 'replace with this'
        'width="*"' => 'width="730px"',
        'height="*"' => 'height="486px"'

    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
add_filter('the_content', 'replace_content_on_the_fly');
add_filter('the_excerpt', 'replace_content_on_the_fly');

However,it doesn't seem to work, anyone know to fix it?

1
  • Fix the formatting of the code please. Jul 26, 2014 at 6:52

1 Answer 1

0

Well if you are trying to replace width="" where "" means empty, you do not need to use "*" when using str_replace, as str_replace do not support regular expression. In that case you function will be as :

function replace_content_on_the_fly($text){
    $replace = array(
        // 'words to find' => 'replace with this'
        'width=""' => 'width="730px"',
        'height=""' => 'height="486px"'

    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
} 

If you want to replace all width height what so ever is between "", you need to use preg_replace

function replace_content_on_the_fly($text){
      $newWidth = 730;
          $newHeight = 486;        

$text = preg_replace(
   array('/width="\d+"/i', '/height="\d+"/i'),
   array(sprintf('width="%d"', $newWidth), sprintf('height="%d"', $newHeight)),
   $text);

        return $text;
    } 
5
  • the width="" or height="" suppose not empty,suppose to have "star" sign for every number (width="450px",width="320px",etc),but when I typed it here, the star sign in middle missing
    – user31445
    Jul 26, 2014 at 7:20
  • @user31445 if width and height are not empty use preg_replace instead of str_replace. Jul 26, 2014 at 7:27
  • Is this the right one? function replace_content_on_the_fly($text){ $replace = array( // 'words to find' => 'replace with this' 'width="*"' => 'width="730px"', 'height="*"' => 'height="486px"' ); $text = preg_replace(array_keys($replace), $replace, $text); return $text; }
    – user31445
    Jul 26, 2014 at 7:32
  • @user31445 Check i have edited my answer with updated preg_replace function.. Jul 26, 2014 at 7:36
  • @user31445 You can accept the answer if helpfull.. Jul 30, 2014 at 10:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.