Jump to content

preg_replace and string


christa

Recommended Posts

hi all

 

why this code doesn't work?

 

$string = "some words here, 12654124";
$pieces = explode(",", $string);
for ($i=0; $i<=1; $i++){
  $pieces[0] = preg_replace("/[^A-Za-z ]$/", "text to be replace", $pieces[0]); 
  echo $pieces[0] . "<br>";
}

 

It returns:

some words here
some words here

 

The right result would be:

 

"text to be replace, 12654124"

Link to comment
https://forums.phpfreaks.com/topic/227900-preg_replace-and-string/
Share on other sites

What exactly are you trying to replace?  It should look something like:

ini_set ("display_errors", "1");
error_reporting(E_ALL);

$string = "some words here, 12654124";
$pieces = explode(",", $string);
foreach($pieces as $key => $value)
{
   $value = preg_replace("/[a-z]+[a-z ]+/", "text to be replace", $value); 
   echo $value . "
";
}
?>

Output:

text to be replace

12654124

i tried your code but I need of an output as this one:

text to be replace 1, 12654124
text to be replace 2, 120025
text to be replace 3, 3509955
text to be replace N, 12654124...

 

I've used a code as this:

$string = "every chars , 12654124";
$pieces = explode(",", $string);
foreach($pieces as $key => $value) {
    for ($i = 0; $i <= 1; $i++) {
        $value = preg_replace("/[a-zA-Z]+[a-zA-Z ]+/", "text to be replace $i", $value);
        echo $value . "<br />";
    }
}

 

but it returns:

text to be replace 0
text to be replace 10
12654124
12654124

 

 

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.