PHP - Get % of a sentence in whole words -


so, have this, fails when trying sentence more 6 words.

what i've done far:

// sentence $str = "hello stack overflow"; // split words delimiter being space $split = explode(" ", $str); // count strings , divide number 3 $divider = str_word_count($str) / 3;  $last2 = $split[count($split)-$divider]; // penultimate word $last1 = $split[count($split)-1]; // last word  // if $ divider gets penultimate word (don't more that) if ($divider < 2){     echo $last2 . " " . $last1 . "<br>";} //echo last 2 words else {     echo $last2 . " " . $split[count($split)-2] . " " . $last1 . "<br>";} //echo last 3 words 

it gets "stack overflow", far good.

what looking way this: enter image description here

thanks

<?php  $str = 'hello stack overflow!';  $parts = explode(' ',preg_replace('/\s+/',' ',$str)); $index = round(count($parts)*0.7); $remaining = array_splice($parts,$index); // parts passed reference &  echo 'first line: '.implode(' ',$parts); echo "\n"; echo 'last line: '.implode(' ',$remaining);  ?> 

prints:

first line: hello stack last line: overflow! 

you're using explode correctly, use array_splice modify original exploded array chop off last 30% (leaving 70%, hence 0.7 multiplier). implode both parts put them together.

honestly though, i'm not sure use case there question (and solution). i'm betting xy problem , op hasn't provided enough contextual information.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -