Amaynut
Amaynut

Reputation: 4271

Extract n-character substring while ignoring spaces

I need to extract a substring (for instance 22 characters) but I need to ignore spaces when counting the number of characters. For example:

$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.";

Let's say I need to get the substring that contains the 22 first characters but without counting the spaces. substr doesn't work:

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

But I need to get

// => While still in high school

How can I do this?

Upvotes: 1

Views: 2431

Answers (4)

Nghị Nguyễn
Nghị Nguyễn

Reputation: 1

You can try this, it is my code, $result is final string you want :

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

Upvotes: 0

vks
vks

Reputation: 67988

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

Try this.Grab the capture or group.See demo.

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

This uses lookahead to capture 20 groups of any character and a non space character. Precisely,lookahead will search for groups ending with non space character.Because it is non greedy,it will search first such 20 groups.

Upvotes: 1

mti2935
mti2935

Reputation: 12027

First, use str_replace() to create a string $parawithoutspaces that consists of $para, without the spaces, like so:

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

Then, use substr() get the first 20 characters of $parawithoutspaces like so:

print substr($parawithoutspaces, 0, 20);

Or, combining the two steps into one and eliminating the need for the intermediate variable $parawithoutspaces:

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

Upvotes: 0

Mubin
Mubin

Reputation: 4445

you just need to provide a string and length you want to be extracted from that string and function will return that string of specified length(yes return string will have spaces in it, but spaces won't be included in string).

Here is snippet.

$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

Upvotes: 0

Related Questions