使用特定分隔符截断PHP字符串

时间:2016-01-05 05:26:41

标签: php function

早上好,

我需要截断一个带有特定分隔符的字符串。 例如,使用该字符串:

myString = 'customname_489494984';

我想在“_”之后自动剥离每个字符串部分 (在本案例中为“489494984”)。

是否有一个函数可以截断特定的字符串部分 定界符?

非常感谢!

弗朗索瓦

4 个答案:

答案 0 :(得分:3)

您还可以使用strstr()查找第一次出现的字符串:

$myString= "customname_489494984";
echo strstr($myString, '_', true);

以下是我的参考:http://php.net/manual/en/function.strstr.php

答案 1 :(得分:1)

使用substrstrpos的简单组合:

$myString = 'customname_489494984';
echo substr($myString, 0, strpos($myString, '_'));

BONUS - 将其包装在自定义功能中:

function truncateStringAfter($string, $delim)
{
    return substr($string, 0, strpos($string, $delim));
}
echo truncateStringAfter('customname_489494984', '_');

答案 2 :(得分:0)

试试这个,它将删除" _"。

之后的任何内容
$string= 'customname_489494984';
$string=substr($string, 0, strrpos($string, '_'));

答案 3 :(得分:0)

其他简单方法的问题是,如果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);
  }

}