Jump to content

Recommended Posts

I have a string that contains sizes

width="xxx" height="yyy"

 

How can I use str_replace to change all of them to

width="400" height="319"

if all the sizes differ?

 

I cannot use:

$object=$_POST['objectdetail'];
$object=str_replace('%body%', '400', 'width="%body%"');
$object=str_replace('%bodya%', '319', 'height="%bodya%"');

 

Please help

Link to comment
https://forums.phpfreaks.com/topic/198001-str_replace-wildcard/
Share on other sites

Try:

 

$reg = '#width="[0-9]+" height="[0-9]+">#/i';

 

This means, "match one or more digits inside the quotes" and the /i is for case insensitivity.

 

Before you were using:

 

[^"]*

 

which doesn't really do anything.  It literally translates to, "match zero or more not quotes".  You may even get an error.

I tried it now as follow:

$object=trim($_POST['object']);
$reg = '#width="[0-9]+" height="[0-9]+"#/i';
$rep='width="400" height="319"';
$object=preg_replace($reg,$rep,$object);
error_reporting(E_ALL);
echo $object;

 

And nothing happens... My string is now gone???

I am now doing an echo before the preg_replace and after....

Only the first echo prints, the second does not?

 

Any idea why?

 

$object=trim($_POST['object']);
echo $object;
$reg = '#width="[0-9]+" height="[0-9]+"#/i';
$rep='width="400" height="319"';
$object=preg_replace($reg,$rep,$object);
echo $object;
error_reporting(E_ALL);

Sorry, my code was erroneous.  Try this:

 

$object=trim($_POST['object']);
echo $object;
$reg = '#width="[0-9]+" height="[0-9]+"#i';
$rep='width="400" height="319"';
$object=preg_replace($reg,$rep,$object);
echo $object;

 

Took out the '/' from the regex.  We don't need it because we're using the '#' as delimiters.

Also, when you're displaying error_reporting you should put it at the top, because anything above it will not be parsed.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.