Jump to content

str_replace wildcard?


StefanRSA

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.