This article mainly introduces the PHP replacement string intermediate character is the ellipsis method, can be implemented to replace the middle part of the string with the ellipsis function, applicable to the account, cell phone number and other sensitive information of the hidden parts, the need for friends can refer to the next
The example in this article describes the method of omitting the intermediate characters of the PHP replacement string. Share to everyone for your reference. The specific analysis is as follows:
For a long string, if you just want the user to see part of the tail and the middle, you can use this PHP function, he can specify the number of intermediate strings to hide
/** * Reduce A string by the middle, keeps whole words together * * @param string $string * @param int $max (default 50) * @param string $replacement (default [...]) * @return String * @author david at ethinkn dot com * @author Loic in XHTML do T ne * @author Arne dot hartherz at gmx dot net */function strmiddlereducewordsensitive ($string, $max =50, $rep = ' [...] ') {$strlen = strlen ($string); if ($strlen <= $max) return $string; $lengthtokeep = $max-strlen ($rep); $start = 0; $end = 0; if ($lengthtokeep% 2) = = 0) {$start = $lengthtokeep/2; $end = $start; } else {$start = Intval ($lengthtokeep/2); $end = $start + 1; } $i = $start; $tmp _string = $string; while ($i < $strlen) {if (Isset ($tmp _string[$i]) and $tmp _string[$i] = = ") {$tmp _string = substr ($tmp _strin G, 0, $i). $rep; $return = $tmp _string; } $i + +; } $i = $end; $tmp _string = Strrev ($string); while ($i < $strlen) {if (Isset ($tmp _string[$i]) and $tmp _string[$i] == ') {$tmp _string = substr ($tmp _string, 0, $i); $return. = Strrev ($tmp _string); } $i + +; } return $return; Return substr ($string, 0, $start). $rep. substr ($string,-$end);}
Demo Example:
Example: $text = ' This was a very long test sentence, bla foo bar nothing ';p rint strmiddlereducewordsensitive ($text, 30) . "\ n";//Returns:this is a very[...] Foo Bar Nothing (~ chrs) Print strmiddlereducewordsensitive ($text, 30, ' ... '). "\ n";//Returns:this is a very...foo bar nothing (~ chrs)