php - How to count the first 30 letters in a string ignoring spaces -


i want take post description display first, example, 30 letters ignore tabs , spaces.

$msg = 'i need first, let say, 30 characters; time being.'; $msg .= ' need remove spaces out of checking.';  $amount = 30;  // if tabs or spaces exist, alter amount if(preg_match("/\s/", $msg)) {     $stripped_amount = strlen(str_replace(' ', '', $msg));     $amount = $amount + (strlen($msg) - $stripped_amount); }  echo substr($msg, 0, $amount); echo '<br /> <br />'; echo substr(str_replace(' ', '', $msg), 0, 30); 

the first output gives me 'i need first, let say, 30 characters;' , second output gives me: ionlyneedthefirst,letusjustsay know isn't working expected.

my desired output in case be:

i need first, let 

thanks in advance, maths sucks.

you part first 30 characters regular expression:

$msg_short = preg_replace('/^((\s*\s\s*){0,30}).*/s', '$1', $msg); 

with given $msg value, in $msg_short:

i need first, let say

explanation of regular expression

  • ^: match must start @ beginning of string
  • \s*\s\s* non-white-space (\s) surrounded 0 or more white-space characters (\s*)
  • (\s*\s\s*){0,30} repeat finding sequence 30 times (greedy; many possible within limit)
  • ((\s*\s\s*){0,30}) parentheses make series of characters group number 1, can referenced $1
  • .* other characters. match remaining characters, because of s modifier @ end:
  • s: makes dot match new line characters well

in replacement characters maintained belong group 1 ($1). rest ignored , not included in returned string.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -