用于从SIP标头中提取SIP号的正则表达式

用于从SIP标头中提取SIP号的正则表达式

问题描述:

Possible SIP from headers:

"unknown-caller-name" <sip:unknown-ani@pbx.domain.com:5066;user=phone>
"Henry Tirta" <sip:951@domain.com>

I need to extract SIP Number between <sip: & @ from the above header in php using regex. This SIP number length will vary.

$from = "\"User Name\" <sip:199@pbx.testdomain.com>";
$matches = array();
$pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/';
preg_match($pattern,$from,$matches);
$number = explode('@', $matches[0])[0];
echo $number;

Any better way to do this ?

标题中可能的SIP: p>

 “unknown-caller- 姓名“&lt; sip:unknown-ani@pbx.domain.com:5066; user = phone&gt; 
”Henry Tirta“&lt; sip:951@domain.com> 
  code>  pre> 
  
 

我需要在&lt; sip: code>&amp;之间提取SIP号码。 使用正则表达式从php中的上述标题中的 @ code>。 此SIP号码长度将有所不同。 p>

  $ from =“\”User Name \“&lt; sip:199@pbx.testdomain.com>”; 
 $ matches =  array(); 
 $ pattern ='/ [A-Z-z0-9_-] + @ [A-Z-z0-9_-] + \。([A- Za-z0-9--] [A-  Za-z0-9 _] +)/'; 
preg_match($ pattern,$ from,$ matches); 
 $ number = explode('@',$ matches [0])[0]; 
echo $ number;  
  code>  pre> 
 
 

有更好的方法吗? p> div>

Let's make it simple:

$from = '"unknown-caller-name" <sip:unknown-ani@pbx.domain.com:5066;user=phone>';
if(preg_match('#<sip:(.*?)@#', $from, $id)){
    echo $id[1];
}else{
    echo 'no match';
}

Explanation:

  • <sip: : match <sip:
  • (.*?) : match and group everything ungreedy until ...
  • @ : @ is found/matched.

I don't know if it's a better way, but I did something shorter, and I used a named group in the regular expression

<?php
$pattern='/^(.*) <sip\:(?P<number>[0-9]+)@(.*)>$/';
$subject='"User Name" <sip:199@pbx.testdomain.com>';
preg_match($pattern,$subject,$matches);
echo $matches["number"];
?>

You can improve the expression by changing the (.*) parts, but I didn't know if you needed something specific for this

I hope this will help you, good luck with your code

$string = '"User Name" <sip:199@pbx.testdomain.com>';

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

// Output
array (size=3)
  0 => string '"User Name" <sip:199@' (length=21)
  1 => string 'User Name' (length=9)
  2 => string '199' (length=3)