在忽略空格的同时提取n字符子字符串

时间:2015-08-03 16:31:46

标签: php regex

我需要提取一个子字符串(例如22个字符),但在计算字符数时我需要忽略空格。例如:

$para = "While still in high school I signed up to participate in amateur night at the Educational Alliance. I wanted to show my mother I had talent.";

让我们说我需要获取包含22个第一个字符但不计算空格的子字符串。 substr无效:

echo substr($para, 0, 22); // => While still in high sc

但我需要得到

// => While still in high school

我该怎么做?

4 个答案:

答案 0 :(得分:1)

首先,使用str_replace()创建一个字符串$ parawithoutspaces,它由$ para组成,没有空格,如下所示:

$parawithoutspaces=str_replace(" ", "", $para);

然后,使用substr()获取$ parawithoutspaces的前20个字符,如下所示:

print substr($parawithoutspaces, 0, 20);

或者,将这两个步骤合二为一,消除了对中间变量$ parawithoutspaces的需求:

print substr(str_replace(" ", "", $para),0,20);

答案 1 :(得分:0)

^(?=((?>.*?\S){20}))

试试这个。抓住捕获或组。参见演示。

https://regex101.com/r/fM9lY3/42

这使用lookahead来捕获20的{​​{1}}组。准确地说,先行将搜索以any character and a non space character字符结尾的组。由于它不贪心,它将首先搜索此类non space组。

答案 2 :(得分:0)

你只需要提供一个string和你希望从string中提取的长度,函数将返回指定长度的字符串(是的返回字符串将包含空格,但空格已赢不包括在字符串中。

这是片段。

$para = "While still in high school I signed up to participate in amateur night at the Educational Alliance. I wanted to show my mother I had talent.";
function getString($str, $length){
    $newStr = "";
    $counter = 0;
    $r = array();
    for($i=0; $i<strlen($str); $i++) 
         $r[$i] = $str[$i];

    foreach($r as $char){
        $newStr .= $char;
        if($char != " "){
            $counter += 1;  
        }

        //return string if length reached.
        if($counter == $length){
            return $newStr;
        }
    }
    return $newStr;
}

echo getString($para, 20);
//output: While still in high scho

echo getString($para, 22);
//output: While still in high school

答案 3 :(得分:0)

您可以尝试一下,这是我的代码,$ result是您想要的最终字符串:

$arr1 = substr( $string,0,20);
$arr1 = explode(" ",$arr1);
array_pop($arr1);
$result = implode(" ",$arr1);