Como eu substituo parte de uma string em PHP? [duplicado]
esta pergunta já tem uma resposta aqui:
- Como substituir certas partes do meu fio? 5 respostas
estou a tentar obter os primeiros 10 caracteres de uma string e quero substituir o espaço por '_'
.
tenho
$text = substr($text, 0, 10);
$text = strtolower($text);
Mas não sei o que fazer a seguir.
quero o texto
Isto é ... o teste para a corda.
torna-se
this_ Is_th
57
Author: Peter Mortensen, 2012-09-26
5 answers
Basta usar str_ replace:
$text = str_replace(' ', '_', $text);
Tu farias isto depois das tuas chamadas anteriores substr
e strtolower
assim:
$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);
Mas, se quiseres ficar chique, podes fazê-lo numa linha:
$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));
102
Author: Jonah Bishop, 2012-09-26 15:29:49
Podes tentar
$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);
var_dump($string);
Saída
this_is_th
4
Author: Baba, 2012-09-26 15:22:53
Faz apenas:
$text = str_replace(' ','_',$text)
3
Author: Nelson, 2012-09-26 15:22:31
Isto é provavelmente o que precisas.
$text=str_replace(' ', '_', substr($text,0,10));
3
Author: Zathrus Writer, 2012-09-26 15:23:15
Primeiro tens de cortar a corda em quantos pedaços queres. Em seguida, substitua a parte que você quer:
$text = 'this is the test for string.';
$text = substr($text, 0, 10);
echo $text = str_replace(" ", "_", $text);
Isto irá resultar:
This_ Is_th
1
Author: iceman, 2016-02-09 15:09:12