Alp*_*App 12 php replace preg-replace
我有一个具有名称的数据库,我想在名称空间后使用PHP替换,数据示例:
$x="Laura Smith";
$y="John. Smith"
$z="John Doe";
Run Code Online (Sandbox Code Playgroud)
我想要它回来
Laura
John.
John
Run Code Online (Sandbox Code Playgroud)
Cod*_*key 22
只是将它添加到组合中,我最近学到了这种技术:
list($s) = explode(' ',$s);
Run Code Online (Sandbox Code Playgroud)
我只是做了一个快速的基准测试,因为我之前没有遇到strtok方法,并且strtok比我的list/explode解决方案快了25%,给出了示例字符串.
此外,初始字符串越长/越界定,性能差距就越大.给一个5000字的块,爆炸将产生5000个元素的数组.strtok将只取第一个"元素",并将其余内容留在内存中作为字符串.
所以strtok赢了我.
$s = strtok($s,' ');
Run Code Online (Sandbox Code Playgroud)
The*_*Kid 19
这样做,这将替换空格字符后面的任何内容.也可用于破折号:
$str=substr($str, 0, strrpos($str, ' '));
Run Code Online (Sandbox Code Playgroud)
试试这个
<?php
$x = "Laura Smith";
echo strtok($x, " "); // Laura
?>
Run Code Online (Sandbox Code Playgroud)
没有必要使用正则表达式,只需使用explode方法.
$item = explode(" ", $x);
echo $item[0]; //Laura
Run Code Online (Sandbox Code Playgroud)