PHP:如何从前两次出现的字符之间获取字符串


PHP: How to get a string from between the first two occurences of character

所以假设我有以下代码:

$var = '-77-randomtext-moretext.extension'

因此,除了连字符(-)和扩展名之外,变量中的任何内容都是固定的。

然后我们说,我需要把"-77-"部分作为一根弦。"-77-"表示前两个连字符之间的任何字符,包括连字符本身。

我怎么能这么做?

实现这一点的两种主要方法是explodepreg_filter

拆分:

$varArray = explode( '-', $var );
$string77 = '-' . $varArray[1] . '-'; // equals '-77-'

preg_filter;

$string77 = preg_filter( '/^(-.+-).*$/', '$1', $varArray ); // equals '-77-', or NULL if the string doesn't match

split方法速度较快,但可靠性较差。preg_filter将确保您始终获得所需的数据,或者如果数据不存在,则为NULL,但需要更多的处理。

您可以使用正则表达式:/-(.+?)-/

$var = '-77-randomtext-moretext.extension';
preg_match('/-(.+?)-/', $var, $matches);
echo $matches[0]; // -77-

使用两个strpos()调用之间的距离,并根据这些位置获得substr()

$var = '-77-randomtext-moretext.extension';
$first_pos = strpos($var,'-');
$second_pos = strpos($var,'-',($first_pos+1)); //we offset so we find the second 
$length = ($second_pos+1) - $first_pos; //get the length of the string between these points
echo  substr($var,$first_pos,$length); 

您也可以使用正则表达式(preg_match())或使用explode()方法:

$pieces = explode('-',$var);
$results = '-'.$pieces[0].'-';

但只有当您知道第一个和第二个分隔符相同时,这才有效。

您可以使用:

$parts = explode('-', $var);
$txt = '-' . $parts[1] . '-';