早上好,用特定分隔符截断PHP字符串
我需要用特定的分隔符截断字符串。 例如以该字符串:
myString = 'customname_489494984';
我想每个字符串份后自动剥离“_” (在这种情况下“489494984”)。
是否有一个函数用于在特定的 定界符之后截断字符串部分?
非常感谢!
弗朗索瓦
早上好,用特定分隔符截断PHP字符串
我需要用特定的分隔符截断字符串。 例如以该字符串:
myString = 'customname_489494984';
我想每个字符串份后自动剥离“_” (在这种情况下“489494984”)。
是否有一个函数用于在特定的 定界符之后截断字符串部分?
非常感谢!
弗朗索瓦
试试这个,它会删除任何东西在“_”之后。
$string= 'customname_489494984';
$string=substr($string, 0, strrpos($string, '_'));
其他直截了当的方法的问题是,如果字符串不包含“_”,那么将返回一个空字符串。这是一个小型的StringUtils类(一个较大的类的一部分),它以多字节安全方式通过beforeFirst静态方法实现。
var_dump(StringUtils::beforeFirst("customname_489494984", "_"));
class StringUtils
{
/**
* Returns the part of a string <b>before the first</b> occurrence of the string to search for.
* @param <b>$string</b> The string to be searched
* @param <b>$search</b> The string to search for
* @param <b>$caseSensitive boolean :optional</b> Defines if the search will be case sensitive. By default true.
* @return string
*/
public static function beforeFirst($string,$search,$caseSensitive = true)
{
$firstIndex = self::firstIndexOf($string, $search,$caseSensitive);
return $firstIndex == 0 ? $string : self::substring($string, 0 , $firstIndex);
}
/**
* Returns a part of the string from a character and for as many characters as provided
* @param <b>$string</b> The string to retrieve the part from
* @param <b>$start</b> The index of the first character (0 for the first one)
* @param <b>$length</b> The length of the part the will be extracted from the string
* @return string
*/
public static function substring($string,$start,$length = null)
{
return ($length == null) ? (mb_substr($string, $start)) : ($length == 0 ? "" : mb_substr($string, $start , $length));
}
/**
* Return the index of <b>the first occurance</b> of a part of a string to the string
* @param <b>$string</b> The string to be searched
* @param <b>$search</b> The string to search for
* @param <b>$caseSensitive boolean :optional</b> Defines if the search will be case sensitive. By default true.
* @return number
*/
public static function firstIndexOf($string,$search,$caseSensitive = true)
{
return $caseSensitive ? mb_strpos($string, $search) : mb_stripos($string, $search);
}
/**
* Returns how many characters the string is
* @param <b>$string</b> The string
* @return number
*/
public static function length($string)
{
return mb_strlen($string);
}
}
您还可以使用的strstr(),它发现一个字符串的第一次出现:
$myString= "customname_489494984";
echo strstr($myString, '_', true);
这是最好的答案。添加一个链接到PHP文档的strstr(),它是完美的。 – mopo922
@ mopo922,我编辑了我的答案并添加了我的参考链接。谢谢! –
AFER ** - ** **或** _ ? :) –
@阿里,后'_'。我编辑了我的答案 – user3040610
好吧。我只是说。我知道这是一个输入错误。 –