PHP从字符串中剥离出特定的文本


PHP stripping out specific text from string

我认为我做这件事的方式不对,但以下是我正在做的。

我有一个从PBX传给我的字符串,我试图只获取电话号码,甚至双引号内的文本(如果存在的话)。

<?php
  $string = '"John Smith" <sip:15558740205@pbx.domain.co:5060;user=phone>';
?>

我确信使用正则表达式的形式会更好地在单独的变量中获取数字和名称,但由于我还不太擅长正则表达式,所以我求助于explode()

我对它做得不太好,它在@符号处分解字符串,然后在:处分解字符串。这就留下了名字。

我该如何去掉<sip:之后@之前的数字?

您可能要做的第一件事是(使用regexp)将<sip: 之前和之后的部分拆分

^(.*?)'s*<sip':(.+)>'s*$

's*意味着跳过任何空白(如果有的话)。

匹配的电话号码是:'d+[0-9]{1,}或您喜欢的任意组合。

如果你可以相信""的内容总是在那里,那么匹配它们将是微不足道的:'s*"([^"]+)"'s*,或者如果它们只是可选的,则会更糟:'s*(?:"([^"]+)"'s*)?

所以让我们把它放在一起:

$regex = '~^'s*(?:"([^"]+)"'s*)?<sip:('d+)@.+>'s*~i';
$matches = array();
if( preg_match($regex, $string, $matches)){
    list(, $name, $phone) = $matches;
}

以下是如何使用regexp:

preg_match('/(?:"([^"]*)")?'s*<.*sip:('d+')/', $string, $match);
$name = $match[1];
$phone = $match[2];
if (preg_match('/^(?:'"([^'"]+)'" )?'<sip':('d+)'@/i', $string, $matches))
    list(, $name, $phone) = $matches;
<sip:([0-9]{1,})@

是您需要的正则表达式

preg_match('/".*?" <sip:([0-9]+)@/', $string, $matches); 
//matches[1] contains the name
//matches[2] contains the number
check this
<?php
  $string = '"John Smith" <sip:15558740205@pbx.domain.co:5060;user=phone>';
  $first = explode("<sip:", $string);
  $second =  explode("@", $first[1]);
  echo $second[0];
?>