Home  >  Article  >  Backend Development  >  How to remove numbers from string in php?

How to remove numbers from string in php?

青灯夜游
青灯夜游Original
2020-09-01 12:00:323139browse

php中,可以使用preg_replace()函数配合正则表达式来删除字符串中的数字;语法为“preg_replace("/\\d+/",'',指定字符串)”或“preg_replace( '/[0-9]/', '',指定字符串);”。

How to remove numbers from string in php?

推荐:《PHP视频教程

可以使用preg_replace()函数来删除字符串中的数字字符。此函数执行正则表达式搜索和替换。函数preg_replace()搜索由pattern(要搜索的模式)指定的字符串,如果找到则用替换替换模式。

php去除字符串中数字的方法:

preg_replace("/\\d+/",'', 指定字符串);
preg_replace( '/[0-9]/', '', 指定字符串);

示例1:

<?php
// 包含数字字符的字符串
$str="php.cn2020"; 
// preg_replace函数删除数字字符
$str = preg_replace( &#39;/\\d+/&#39;, &#39;&#39;, $str);  
//打印字符串
echo($str); 
?>

输出:

php.cn

示例2:

<?php
// 包含数字字符的字符串
$str="php.cn2020"; 
// preg_replace函数删除数字字符
$str = preg_replace( &#39;/[0-9]/&#39;, &#39;&#39;, $str);  
//打印字符串
echo($str); 
?>

输出:

php.cn

preg_replace 函数介绍

preg_replace 函数执行一个正则表达式的搜索和替换。

(推荐教程:php图文教程

语法:

preg_replace(mixed $pattern, mixed $replacement, mixed $subject[, int $limit = -1[, int &$count]])

参数:

  • $pattern: 要搜索的模式,可以是字符串或一个字符串数组。

  • $replacement: 用于替换的字符串或字符串数组。

  • $subject: 要搜索替换的目标字符串或字符串数组。

  • $limit: 可选,对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是-1(无限制)。

  • $count: 可选,为替换执行的次数。

返回值:

如果 subject 是一个数组, preg_replace() 返回一个数组, 其他情况下返回一个字符串。如果匹配被查找到,替换后的 subject 被返回,其他情况下 返回没有改变的 subject。如果发生错误,返回 NULL。

The above is the detailed content of How to remove numbers from string in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn