本文介绍了从 php regex 中提取匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 perl regex 中,我们可以提取匹配的变量,例如下面.
In perl regex we can extract the matched variables, ex below.
# extract hours, minutes, seconds
$time =~ /(dd):(dd):(dd)/; # match hh:mm:ss format
$hours = $1;
$minutes = $2;
$seconds = $3;
如何在 php 中执行此操作?
How to do this in php?
$subject = "E:[email protected] I:100955";
$pattern = "/^E:/";
if (preg_match($pattern, $subject)) {
echo "Yes, A Match";
}
如何从那里提取电子邮件?(我们可以爆炸它并得到它……但想要一种直接通过正则表达式得到它的方法)?
How to extract the email from there? (We can explode it and get it...but would like a method to get it directly through regex)?
推荐答案
尝试使用 preg_match 的命名子模式语法:
Try using the named subpattern syntax of preg_match:
<?php
$str = 'foobar: 2008';
// Works in PHP 5.2.2 and later.
preg_match('/(?<name>w+): (?<digit>d+)/', $str, $matches);
// Before PHP 5.2.2, use this:
// preg_match('/(?P<name>w+): (?P<digit>d+)/', $str, $matches);
print_r($matches);
?>
输出:
Array (
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008 )
这篇关于从 php regex 中提取匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!