我喜欢MySQL中的SUBSTRING_INDEX函数,特别是因为您可以使用负索引从字符串的右侧开始搜索。
在PHP中有与此函数等效的函数吗?(或者用一小段代码来实现的一种简单方法)
发布于 2011-07-31 04:40:54
没有一个库函数可以提供相同的功能,但您可以获得一行代码:
$str = "www.mysql.com";
echo implode('.', array_slice(explode('.', $str), 0, 2)); // prints "www.mysql"
echo implode('.', array_slice(explode('.', $str), -2)); // prints "mysql.com"轻松地将其转换为函数:
function substring_index($subject, $delim, $count){
if($count < 0){
return implode($delim, array_slice(explode($delim, $subject), $count));
}else{
return implode($delim, array_slice(explode($delim, $subject), 0, $count));
}
}发布于 2013-05-23 23:41:40
我认为
string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )是适合你的php函数。
strstr -查找字符串的第一个匹配项
<?php
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>发布于 2014-12-10 00:26:10
我很好奇,并使用preg/match设置测试了另一种方法,然后对其进行了重构,以允许任意数量的分隔符/计数。我添加了另一个示例使用的计数检查,但我可能还会建议对分隔符字段进行某种清理。
function substring_index($subject, $delim, $count){
if($count < 0){
$notRe = '[^\\'.$delim.']*';
$elem = array();
for($x=1;$x<=$count;$x++){
array_push($elem,$notRe);
}
$re = '/^('.implode('\\'.$delim,$elem).')/';
preg_match($re, $subject,$m);
if(count($m) == 2) {
return $m[1];
}
}
}https://stackoverflow.com/questions/6885793
复制相似问题