Last active
May 28, 2021 22:24
-
-
Save iniznet/3b050b4fbdc20315680e723f785456d2 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Split string and wrap text with preserving html | |
* | |
*/ | |
function html_wrap( string $string, bool $output_array = true, int $width = 30, string $break = " \r\n" , bool $cut_long_words = false ) { | |
if ( empty( $string ) ) { | |
return false; | |
} | |
$output = array(); | |
$delimeter = PHP_EOL; | |
// Make a safety for start tag with | | |
$string = preg_replace( '/(<(?!\/).*?>)/', '|$1', $string ); | |
// Make a safety for closing tag with | | |
$string = preg_replace( '/(<\/.*?>)/', '$1|', $string ); | |
// Split the string | |
$str_list = array_filter( explode( '|', $string ) ); | |
foreach( $str_list as $str ) { | |
if ( strpos( $str, '</' ) !== false ) { | |
$output[][] = $str; | |
continue; | |
} | |
$tmp_str = wordwrap( $str, $width, $break, $cut_long_words ); | |
$output[] = preg_split( "/($delimeter)/", $tmp_str ); | |
} | |
if ( !$output_array ) { | |
$output = iterator_to_array( new \RecursiveIteratorIterator(new \RecursiveArrayIterator($output) ), false ); | |
$output = join( "", $output ); | |
} | |
return $output; | |
} | |
print_r( html_wrap( 'Seeing Meng You remain silent, Yan Ke coughed <strong>twice</strong>, and used his <strong>slightly hoarse</strong> voice to provoke the prince. Yan Ke: "Look, I’ve made such a huge offense, your Yue Kingdom definitely won’t keep me alive, right? You must be a benevolent king~"' ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment