Created
March 29, 2011 22:51
-
-
Save aaronpk/893524 to your computer and use it in GitHub Desktop.
Selectively trim text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $examples[] = 'This is text with no trim components'; | |
| $examples[] = 'This text is short but has /--trim components --/ too.'; | |
| $examples[] = 'This text is going to be quite long and has some parts that can be removed, /--such as this one, --/ and some that can\'t.'; | |
| $examples[] = 'This text is /-2-quite --/long and has some parts that can be removed, /-1-such as this one, --/ and some that can\'t.'; | |
| $trimLength = 100; | |
| foreach($examples as $example) { | |
| echo '<hr />'; | |
| if(strlen($example) > $trimLength) { | |
| if(preg_match_all('#/-([0-9]{0,2})-(.+?)--/#', $example, $matches)) { | |
| $trimmed = $example; | |
| $j = 0; | |
| $removalCandidates = array(); | |
| foreach($matches[0] as $i=>$m) { | |
| if($matches[1][$i] != '') { | |
| $k = intval($matches[1][$i]); | |
| } | |
| else { | |
| $k = count($removalCandidates); | |
| } | |
| $removalCandidates[$k] = $m; | |
| } | |
| ksort($removalCandidates); | |
| $tmp = array(); | |
| foreach($removalCandidates as $r) | |
| $tmp[] = $r; | |
| $removalCandidates = $tmp; | |
| $i = 0; | |
| while(strlen(removeTrimTags($trimmed)) > $trimLength && $i < count($removalCandidates)) { | |
| $trimmed = str_replace($removalCandidates[$i], '', $trimmed); | |
| $i++; | |
| } | |
| } | |
| } else { | |
| $matches = 'not trimmed'; | |
| $trimmed = $example; | |
| } | |
| // Remove any remaining trim tags | |
| $trimmed = removeTrimTags($trimmed); | |
| echo $example . '<br />'; | |
| #echo '<pre>'; print_r($matches); echo '</pre>'; | |
| echo $trimmed . '<br />'; | |
| } | |
| function removeTrimTags($text) { | |
| return preg_replace(array('#/-([0-9]{0,2})-#','#--/#'), '', $text); | |
| } | |
| /** | |
| Output: | |
| This is text with no trim components | |
| This is text with no trim components | |
| This text is short but has /--trim components --/ too. | |
| This text is short but has trim components too. | |
| This text is going to be quite long and has some parts that can be removed, /--such as this one, --/ and some that can't. | |
| This text is going to be quite long and has some parts that can be removed, and some that can't. | |
| This text is /-2-quite --/long and has some parts that can be removed, /-1-such as this one, --/ and some that can't. | |
| This text is quite long and has some parts that can be removed, and some that can't. | |
| **/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment