本篇文章是对如何在PHP中使用正则表达式进行查找替换进行了详细的分析介绍,需要的朋友参考下
1. preg_match — 执行一个正则表达式匹配
复制代码 代码如下:
/*
*模式分隔符后的"i"标记这是一个大小写不敏感的搜索
*将会输出:1
*/
echo preg_match("/,\s*(php)/i", "In my point, PHP is the web scripting language of choice.");
echo "
"."\n";
/*
*将会输出:Array([0]=>, PHP [1]=>PHP)
*/
$matches = array();
preg_match("/,\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches);
print_r($matches);
echo "
"."\n";
/*
*将会输出:Array([0]=>Array([0]=>, PHP [1]=>11) [1]=>Array([0]=>PHP [1]=>13))
*/
preg_match("/,\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
echo "
"."\n";
/*
*将会输出:Array([0]=>Array([0]=>e php [1]=63) [1]=>Array([0]=>php [1]=>65))
*/
preg_match("/[,a-z]?\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_OFFSET_CAPTURE, 28);
print_r($matches);
echo "
"."\n";
?>
复制代码 代码如下:
/*
*将会输出:2
*/
echo preg_match_all("/php/i", "In my point, PHP is the web scripting language of choice. I love php", $matches);
echo "
"."\n";
/*
*将会输出:Array([0]=>, PHP [1]=>PHP)
*/
$matches = array();
preg_match("/[,a-z]?\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches);
print_r($matches);
echo "
"."\n";
/*
*将会输出:Array([0]=>Array([0]=>, PHP [1]=>e php) [1]=>Array([0]=>PHP [1]=>php))
*/
$matches = array();
preg_match_all("/[,a-z]?\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_PATTERN_ORDER);
print_r($matches);
echo "
"."\n";
/*
*将会输出:Array([0]=>Array([0]=>Array([0]=>, PHP [1]=>11) [1]=>Array([0]=>PHP [1]=>13)) [1]=>Array([0]=>Array([0]=>e php [1]=>63) [1]=>Array([0]=>php [1]=>65)))
*/
$matches = array();
preg_match_all("/[,a-z]?\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
print_r($matches);
echo "
"."\n";
/*
*Array([0]=>Array([0]=>e php [1]=>63) [1]=>Array([0]=>php [1]=>65))
*/
$matches = array();
preg_match_all("/[,a-z]?\s*(php)/i", "In my point, PHP is the web scripting language of choice. I love php", $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE, 28);
print_r($matches);
echo "
"."\n";
?>
复制代码 代码如下: