如何在 PHP 中替换部分字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12605060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace part of a string in PHP?
提问by Rouge
I am trying to get the first 10 characters of a string and want to replace space with '_'.
我正在尝试获取字符串的前 10 个字符,并希望将空格替换为'_'.
I have
我有
$text = substr($text, 0, 10);
$text = strtolower($text);
But I am not sure what to do next.
但我不确定接下来要做什么。
I want the string
我想要字符串
this is the test for string.
这是对字符串的测试。
become
变得
this_is_th
this_is_th
回答by Jonah Bishop
Simply use str_replace:
只需使用str_replace:
$text = str_replace(' ', '_', $text);
You would do this after your previous substrand strtolowercalls, like so:
您可以在之前的substr和strtolower调用之后执行此操作,如下所示:
$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);
If you want to get fancy, though, you can do it in one line:
但是,如果您想变得花哨,可以在一行中完成:
$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));
回答by Baba
You can try
你可以试试
$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);
var_dump($string);
Output
输出
this_is_th
回答by Zathrus Writer
This is probably what you need:
这可能是你需要的:
$text = str_replace(' ', '_', substr($text, 0, 10));
回答by Nelson
Just do:
做就是了:
$text = str_replace(' ', '_', $text)
回答by iceman
You need first to cut the string in how many pieces you want. Then replace the part that you want:
你首先需要把绳子剪成你想要的几段。然后更换你想要的部分:
$text = 'this is the test for string.';
$text = substr($text, 0, 10);
echo $text = str_replace(" ", "_", $text);
This will output:
这将输出:
this_is_th
this_is_th

