PHP str replace reemplazar espacios con guiones bajos
¿Hay una razón que no estoy viendo, por qué esto no funciona?
$journalName = $_POST['journalName'];
$journalName = str_replace(' ', '_', $journalName);
$_SESSION['journalName'] = $journalName;
echo $_SESSION['journalName'];
La salida todavía incluye espacios... Cualquier idea sería impresionante
32
4 answers
Sugeriré que use esto ya que comprobará la ocurrencia simple y múltiple de espacios en blanco (como sugirió Lucas Green).
$journalName = preg_replace('/\s+/', '_', $journalName);
En lugar de:
$journalName = str_replace(' ', '_', $journalName);
102
Author: Laurent Brieu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-07 12:37:26
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-07 12:37:26
Prueba esto en su lugar:
$journalName = preg_replace('/\s+/', '_', $journalName);
Explicación: lo más probable es que veas espacios en blanco, no solo espacios simples (hay una diferencia).
10
Author: Lucas Green,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-03 08:31:09
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-03 08:31:09
Para reemplazar un carácter coincidente, use str_replace :
$string = str_replace(' ', '_', $string);
Para reemplazar todos los caracteres coincidentes, use preg_replace :
$string = preg_replace('/\s+/', '_', $string);
3
Author: Ravi Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 05:13:32
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 05:13:32
Prueba esto en su lugar:
$journalName = str_replace(' ', '_', $journalName);
Para eliminar el espacio en blanco
0
Author: IsaacP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-22 06:11:35
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-22 06:11:35