How to replace spaces in String with underscores?

0
$cadena = "Esta es la cadena que quiero cambiar";
/*
.
.
.El código que lo convierte 
.
.
*/
echo $cadenaconvertida;
  

Result: "Esta_la_cadena_ que_quiero_cambiar"

    
asked by Cesar Velasquez 13.06.2018 в 14:53
source

1 answer

6

You have many alternatives in PHP .

  

strtr:

strtr is used to replace characters consecutively, replacing all occurrences of each character (single byte). This can show "unexpected" results when adding multiple characters as it interprets each character independently. For example:

echo strtr("ABCBADEFG", "BA", "12");
// Resultado: "21C12DEFG"
  • Structure:

string strtr (string $ string , string $ from , string $ to )

string strtr (string $ string , array $ pairs_replace )

  • Response time (average): 40.9357118607 seconds

  • Reference: Here

  

In response:

$cadena = "Esta es la cadena que quiero cambiar";

$cadenaConvert = strtr($cadena, " ", "_");

echo $cadenaConvert;
  

preg_replace:

preg_replace performs a search and substitution of a regular expression.

  • Structure:

mixed preg_replace (mixed $ pattern , mixed $ replacement , mixed $ string [ int $ limit = -1 [ int & $ counter ] ])

  • Response time (average): 3.27423620224 seconds

  • Reference: Here

  

In response:

$cadena = "Esta es la cadena que quiero cambiar";

$cadenaConvert = preg_replace('/\s+/', '_', $cadena);

echo $cadenaConvert;
  

str_replace: (the most recommended and fastest)

str_replace replaces all occurrences of the searched string with the replacement string. This function returns a string or an array with all occurrences of search in subject replaced with the given value of replacement . search and replacement can be a string or an array. In the case of an array, an equivalent is made with the array with the lowest index for substitutions.

  • Structure:

mixed str_replace (mixed $ search , mixed $ replacement , mixed $ subject [ int & $ count ])

  • Response time (average): 1.49082899094 seconds

  • Reference: Here

  

In response:

$cadena = "Esta es la cadena que quiero cambiar";

$cadenaConvert = str_replace(" ", "_", $cadena);

echo $cadenaConvert;
  

Result for all: "This_is_the_chain_to_quire_change"

     

Response time reference: Here

    
answered by 13.06.2018 / 16:52
source