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
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

Link to comment
Share on other sites

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

 

 

Link to comment
Share on other sites

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.