我在数组 $phone 中保存了一个值,并且想要删除 "Tel." 和 " - ". $phone 的原始值是 "Tel. +47 - 87654321" 我希望它是 "+4787654321".
到目前为止我已经编写了这段代码:
$phone = Tel. +47 - 87654321;
echo "<br />"
. str_replace("Tel. ","",($phone->textContent)
. str_replace(" - ","",$phone->textContent));
结果:
+47 - 87654321+4787654321
如何避免打印(回显)此代码的第一部分?这是更好的方法吗?
这对我有用:
echo "<br />" . str_replace(array("Tel. ", " - "), "", $phone->textContent);
不要连接两个函数的结果,因为它们在更改后返回整个字符串。
而是在下次通话中更改它
$string = str_replace("Tel. ", "", $phone->textContent);
$string = str_replace(" - ", "", $string);
或将项目数组传递给
str_replace()
。
$string = str_replace(array("Tel. ", " - "), "", $phone->textContent);
将中间结果分配给变量。尝试:
$temp = str_replace("Tel. ","",($phone->textContent);
echo "<br />". str_replace(" - ","",$temp));
echo preg_replace ("/^(.*)(?=\\+)(.*)$/", "$2", "Tel. +47 - 87654321" )
将输出:
+47 - 87654321
说明:
它使用正则表达式将字符串分为两组:
+
之前的所有字符(使用前瞻)+
之后的任何内容,包括+
然后只用第二组替换它
有多种方法可以完成此任务。由于字符串具有已知的长度和格式,因此您可以实现以下任意操作。
代码:(演示)
删除非数字、非加号字符:
echo preg_replace('/[^\d+]+/', '', $phone);
删除两个已知的文字字符串:
echo str_replace(['Tel. ', ' - '], '', $phone);
删除两个已知的文字字符串:
echo strtr($phone, ['Tel. ' => '', ' - ' => '']);
解析静态和动态段,然后连接:
echo implode(sscanf($phone, 'Tel. %s - %s'));
通过格式化字符串中可预测的偏移量和长度提取子字符串,然后连接:
echo substr($phone, 5, 3) . substr($phone, -8);