简体   繁体   中英

Regex for extracting SIP Number from SIP Header

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 ?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM