PHP从字符串中删除特定文本

时间:2013-07-16 07:20:59

标签: php regex

我想我会以错误的方式解决这个问题,但这就是我正在做的事情。

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

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

我很乐意使用正则表达式的形式更好地在单独的变量中获取数字和名称,但由于我还不太擅长正则表达式,我正在使用explode()

我用它做得不是很好,而且在@标志处爆炸字符串,然后在:处爆炸。这留下了名字。

如何在<sip:之前的@之后删除号码?

5 个答案:

答案 0 :(得分:1)

您可能要做的第一件事是在<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;
}

答案 1 :(得分:0)

以下是使用regexp执行此操作的方法:

preg_match('/(?:"([^"]*)")?\s*<.*sip:(\d+\)/', $string, $match);
$name = $match[1];
$phone = $match[2];

答案 2 :(得分:0)

<sip:([0-9]{1,})@

是你需要的正则表达式

preg_match('/".*?" <sip:([0-9]+)@/', $string, $matches); 
//matches[1] contains the name
//matches[2] contains the number

答案 3 :(得分:0)

if (preg_match('/^(?:\"([^\"]+)\" )?\<sip\:(\d+)\@/i', $string, $matches))
    list(, $name, $phone) = $matches;

答案 4 :(得分:-1)

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];
?>
相关问题