Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中从字符串中提取简单加号和数字_Php_Regex - Fatal编程技术网

如何在php中从字符串中提取简单加号和数字

如何在php中从字符串中提取简单加号和数字,php,regex,Php,Regex,如何使用+simple从字符串中提取电话号码。我的输入是+6594758744(威廉)。我的预期输出是+6594758744 所以我需要从下面的字符串类型中提取+6594758744 $str1='+6594758744(威廉)'$str2='+6594758744(威廉:兄弟)'$str3='+6594758744(威廉:兄弟)'$str4='+6594758744(威廉·艾伦:兄弟)'老实说……这里不需要正则表达式 <?php $str='+6594758744(william)';

如何使用+simple从字符串中提取电话号码。我的输入是+6594758744(威廉)。我的预期输出是+6594758744

所以我需要从下面的字符串类型中提取+6594758744


$str1='+6594758744(威廉)'$str2='+6594758744(威廉:兄弟)'$str3='+6594758744(威廉:兄弟)'$str4='+6594758744(威廉·艾伦:兄弟)'

老实说……这里不需要正则表达式

<?php
$str='+6594758744(william)';
$arr = explode('(',$str);
echo $arr[0]; //"prints" +6594758744

您可以尝试
preg\u replace

$s = '+65 94758744(william)';
$r = preg_replace('/^.*?(\+[\d ]+).*$/', '$1', $s);
//=> +65 94758744
让我们试试

$str = '+6594758744(william) ';
echo "+" . sprintf('%.0f', $str);
试试这个

$str='+6594758744(william)';
$output=preg_replace("/[^0-9]/","",$str);
echo "+".$output;
试试这个

模式是

/(\+\d{10})/
这将捕获电话号码


正则表达式可以捕获加号,后跟数字和空格。然后,结果匹配可以删除空格。例如:

<?php

$strings = array(
  '+6594758744 (william)',
  '+6594758744 (william:brother)',
  '+6594758744 ( william : brother )',
  '+65 94758744 ( william allan:brother )'
);


$regexp = '/((\+)?([\d ]+))/';
foreach ($strings as $string) {
  preg_match($regexp, $string, $matches);
  print preg_replace('/ /', '', $matches[0]) . "\n";
}

谢谢你,它正在工作。。请编辑第二行中的您的答案=>$r=preg\u replace('/^.*?(\+\d+.*$/','$1',$s);你错过了论点中的逗号对不起,这是一个错误,我修正了它。但是输入是+65 94758744(william allan)意味着输出=>+65 Only担心延迟重播上述更新代码也只给出+65如果输入是
$str='+6594758744(william 1st)”,则会给出错误的结果谢谢@anubhava是的,这给出+6565947587441,但在我的字符串中,更罕见的情况是,我将提取前10个数字..我需要通过给出更多差异来测试它values@Anitha我也同意阿努巴瓦的观点。我的建议是:与其假设你不会遇到会破坏你的解决方案的罕见案例,不如稍微努力一点,制定出一个稍微聪明一点的解决方案,也能处理罕见案例。从长远来看,这将使你成为一名更有效的程序员,你会发现自己的头痛更少。@Alvin Lee我通过使用echo“+”.substr($output,0,10)得到答案;也同意您的解决方案Optional=>()对于给定字符串有时我的字符串有括号有时没有括号那么您可以只添加一个空格,而不是上面代码中的
)。
<?php

$strings = array(
  '+6594758744 (william)',
  '+6594758744 (william:brother)',
  '+6594758744 ( william : brother )',
  '+65 94758744 ( william allan:brother )'
);


$regexp = '/((\+)?([\d ]+))/';
foreach ($strings as $string) {
  preg_match($regexp, $string, $matches);
  print preg_replace('/ /', '', $matches[0]) . "\n";
}