Dyl*_*lan 7 php mysql substring
我喜欢SUBSTRING_INDEXMySQL中的函数,特别是因为你可以使用负索引从字符串的右侧开始搜索.
在PHP中是否有相当于这个功能的东西?(或使用一些代码轻松实现)
Mar*_*iot 16
没有单一的库函数可以为您提供相同的功能,但您可以获得一个单行:
$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"
Run Code Online (Sandbox Code Playgroud)
轻松将其转换为功能:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我认为
string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
Run Code Online (Sandbox Code Playgroud)
是适合您的 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
?>
Run Code Online (Sandbox Code Playgroud)