首页后端开发JAVAPHP正则表达式和字符串匹配示例

PHP正则表达式和字符串匹配示例

时间2023-07-05 20:07:02发布访客分类JAVA浏览1143
导读:以下是一些常用的正则表达式函数的示例:// preg_match( $pattern = '/hello/'; $string = 'hello world'; if (preg_match($pattern, $string {...

以下是一些常用的正则表达式函数的示例:

// preg_match()
$pattern = '/hello/';
    
$string = 'hello world';


if (preg_match($pattern, $string)) {
    
    echo 'Match found!';

}
 else {
    
    echo 'Match not found.';

}
    
// 输出:Match found!

// preg_match_all()
$pattern = '/\d+/';
    
$string = 'The number is 12345';


if (preg_match_all($pattern, $string, $matches)) {
    
    echo 'Match found '.$matches[0][0].' times.';

}
 else {
    
    echo 'Match not found.';

}
    
// 输出:Match found 12345 times.

// preg_replace()
$pattern = '/world/';
    
$string = 'hello world';
    

$new_string = preg_replace($pattern, 'PHP', $string);
    

echo $new_string;
    
// 输出:hello PHP

// preg_split()
$pattern = '/\s+/';
    
$string = 'hello world';
    

$words = preg_split($pattern, $string);
    

print_r($words);
    
// 输出:Array([0] =>
     hello [1] =>
     world)

字符串匹配

除了正则表达式之外,PHP还提供了一些字符串匹配函数。这些函数可以用于查找字符串中是否包含某个子串,或者从字符串中提取特定的子串。

以下是一些常用的字符串匹配函数:

  • strpos():在字符串中查找某个子串第一次出现的位置。如果找到,返回子串第一次出现的位置;否则返回false。
  • strrpos():在字符串中查找某个子串最后一次出现的位置。如果找到,返回子串最后一次出现的位置;否则返回false。
  • substr():从字符串中提取子串。第一个参数是要提取的字符串,第二个参数是起始位置,第三个参数是子串的长度。
  • str_replace():替换字符串中的子串。第一个参数是要替换的子串,第二个参数是替换后的子串,第三个参数是要替换的字符串。

以下是一些字符串匹配函数的示例:

// strpos()
$needle = 'world';
    
$haystack = 'hello world';


if (strpos($haystack, $needle) !== false) {
    
    echo 'Match found!';

}
 else {
    
    echo 'Match not found.';

}
    
// 输出:Match found!

// strrpos()
$needle = 'world';
    
$haystack = 'hello world';


if (strrpos($haystack, $needle) !== false) {
    
    echo 'Match found!';

}
 else {
    
    echo 'Match not found.';

}
    
// 输出:Match found!

// substr()
$string = 'hello world';
    

$sub = substr($string, 6, 5);
    

echo $sub;
    
// 输出:world

// str_replace()
$needle = 'world';
    
$replacement = 'PHP';
    
$haystack = 'hello world';
    

$new_string = str_replace($needle, $replacement, $haystack);
    

echo $new_string;
    
// 输出:hello PHP

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

php

若转载请注明出处: PHP正则表达式和字符串匹配示例
本文地址: https://pptw.com/jishu/290708.html
PHP文件的上传和下载(二) PHP文件的上传和下载(一)

游客 回复需填写必要信息