如何在PHP中替换字符串的一部分? [英] How do I replace part of a string in PHP?

查看:363
本文介绍了如何在PHP中替换字符串的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取字符串的前10个字符,并想用'_'替换空格.

I am trying to get the first 10 characters of a string and want to replace space with '_'.

我有

  $text = substr($text, 0, 10);
  $text = strtolower($text);

但是我不确定下一步该怎么做.

But I am not sure what to do next.

我想要字符串

这是对字符串的测试.

this is the test for string.

成为

this_is_th

this_is_th

推荐答案

只需使用您可以在之前的substrstrtolower调用之后执行此操作,就像这样:

You would do this after your previous substr and strtolower calls, like so:

$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)));

这篇关于如何在PHP中替换字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆