PHP 8.5.0 Alpha 2 available for testing

Voting

: max(one, three)?
(Example: nine)

The Note You're Voting On

Daniel Rhodes
11 years ago
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
* Trim singlebyte and multibyte punctuation from the start and end of a string
*
* @author Daniel Rhodes
* @note we want the first non-word grabbing to be greedy but then
* @note we want the dot-star grabbing (before the last non-word grabbing)
* @note to be ungreedy
*
* @param string $string input string in UTF-8
* @return string as $string but with leading and trailing punctuation removed
*/
function mb_punctuation_trim($string)
{
preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

if(count($matches) < 2)
{
//some strange error so just return the original input
return $string;
}

return $matches[1];
}

Hope you like it!

<< Back to user notes page

To Top