php str_replace用法
时间: 2023-07-05 16:15:34 浏览: 54
PHP中的str_replace()函数用于在字符串中替换指定的文本。它的基本语法如下:
```php
str_replace($search, $replace, $subject);
```
其中,$search表示要被替换的文本,$replace表示用于替换的文本,$subject表示要进行替换的原始字符串。
下面是一个例子,将字符串中的所有空格替换为下划线:
```php
$str = "This is a test string.";
$newstr = str_replace(" ", "_", $str);
echo $newstr;
```
输出结果为:
```
This_is_a_test_string.
```
还可以将多个搜索字符串和替换字符串传递给该函数,这些字符串可以作为数组传递。
例如,将字符串中的所有空格和分号替换为下划线和冒号:
```php
$str = "This is a test string; please replace spaces and semicolons.";
$search = array(" ", ";");
$replace = array("_", ":");
$newstr = str_replace($search, $replace, $str);
echo $newstr;
```
输出结果为:
```
This_is_a_test_string:_please_replace_spaces_and_semicolons.
```
相关问题
php中函数的用法 str_replace()
str_replace() 函数用于在字符串中替换指定字符或字符串,用另一个字符或字符串替换它们。语法为:str_replace(search, replace, subject)。其中,search:必需。规定要查找的值。replace:必需。规定要替换查找的值的值。subject:必需。规定被搜索的字符串。
preg_replace(“”,function(){},text)类似的案例
`preg_replace_callback` 函数可以实现类似的功能。
它的用法是:
```php
preg_replace_callback( $pattern, $callback, $subject, $limit = -1, &$count = null )
```
其中,`$pattern` 是正则表达式,`$callback` 是回调函数,`$subject` 是待处理的字符串。当 `$subject` 中匹配到 `$pattern` 时,将会调用 `$callback` 函数来处理匹配到的部分。
下面是一个示例,将字符串中的数字替换成其平方:
```php
$str = "1 2 3 4 5";
$result = preg_replace_callback("/\d+/", function($match) {
return $match[0] * $match[0];
}, $str);
echo $result; // 输出:1 4 9 16 25
```
在上面的示例中,`$pattern` 是 `/\d+/`,表示匹配一个或多个数字。`$callback` 是一个匿名函数,使用 `$match[0]` 来获取匹配到的数字,再将其平方后返回。`$subject` 是 `"1 2 3 4 5"`,表示需要处理的字符串。
当 `preg_replace_callback` 函数执行时,会匹配到 `"1"`、`"2"`、`"3"`、`"4"` 和 `"5"` 这五个数字,然后分别调用 `$callback` 函数处理。最终,将会得到一个新的字符串 `"1 4 9 16 25"`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)