Jump to content

difference between two constructions in preg_replace


hisoka

Recommended Posts

In this little code :

<?php

if (isset($_GET['animal']))
{
      $string =$_GET['animal'];
      $replacement = 'cat';
      if (strpos($string, 'mouse') !==false)
         {
     echo preg_replace('/.$string./' , $replacement, 'mouse');
         }
}

?>

the result is mouse

 

Now when I replace

'/.$string./'

with

"/".$string."/"

I got cat as a result .

 

I do not know what is the difference between

 "/".$string."/" 

and

'/.$string./'

and what are both dots in

'/.$string./'

and

"/".$string."/" 

used for ?

Edited by hisoka
Link to comment
Share on other sites

Thank you for the link

 

I will reformulate my question :

 

why is

"/".$string."/"

in four double quotes and not between two double quotes like this :

"/.$string./"

??

 

Could you please explain to me why the

$string

in

'/.$string./'

is between two dots ? in other words what is the role of the two dots ?

Edited by hisoka
Link to comment
Share on other sites

That's literally the string "$string" surrounded by dots and slashes. It is just text, it does not mean anything. I don't know where you found that code but it is wrong. It does not do anything.

Link to comment
Share on other sites

This is correct: It's concatenating the value of the variable with other strings:

"/".$string."/"

This is not correct. Everything between the quotation marks are literally part of the string. There's no variable.

'/.$string./'
Link to comment
Share on other sites

This is not correct. Everything between the quotation marks are literally part of the string. There's no variable.

 

 

I understood it very well

 

What I could not understand is here :

"/".$string."/"

Why we use 4 green double quotes instead of two green double quotes ? or what is the role of the 4 green double quotes ?

Edited by hisoka
Link to comment
Share on other sites

Each pair of double quotes contains a string between them which the syntax highlighter is showing in green. They are two separate independent strings.

This is very basic PHP. Please read the PHP chapter about strings carefully: http://php.net/manual/en/language.types.string.php

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...