How to encompass the first letter in every word with HTML tags?
How to encompass the first letter in every word with HTML tags?
For example:
$string = replace_first_word("some simple text",'<big>{L}</big>');
echo $string; //returns: <big>s</big>ome <big>s</big>imple <big>t</big>开发者_运维技巧ext
edit: ohhh, forgot to mention one important point, it Needs to work with UTF-8 Unicode... because I'm planning to support both Russian and English with this.
Try this:
$string = preg_replace('/(?:^|\b)(\p{L})(\p{L}*)/u', '<big>$1</big>$2', 'some simple words');
Or if you want it in a function:
function replace_first_word($str, $format) {
return preg_replace('/(?:^|\b)(\p{L})(\p{L}*)/u', str_replace('{L}', '$1', $format).'$2', $str);
}
Standard warning: manipulating HTML with regexes is a bad idea because it's next to impossible to correctly handle nesting, content inside tags vs outside, etc. So if you need a complete solution, parse the HTML and then manipulate text nodes.
In this psecific example that you've given, this should do it.
$output = preg_replace('!\b([a-zA-Z])!`, '<big>$1</big>`, $input);
It means find a word boundary (\b
), which is zero width, and wrap the following letter in a <big>
element.
You could use the CSS property
p { text-transform: capitalize; }
From Sitepoint's CSS reference on text-transform:
capitalize
- transforms the first character in each word to uppercase; all other characters remain unaffected — they’re not transformed to lowercase, but will appear as written in the document
i think what you need is
preg_replace('~(?<=\p{^L}|^)\p{L}~u', '<big>$0</big>', $input);
note that \b does not work properly with utf8.
here is a better and possibly faster version that i just found out myself, that supports utf-8 multibyte characters.
in my experience regex functions are slow in php, so here is a string manipulation based function.
function replace_first_word($text,$format='<big>{L}</big>'){
//*** UTF-8 replace first letter of every word ***
//split words
$words = explode(' ', $text);
//pick up each word
foreach($words as &$word){
//find out first letter of word
$first = substr($word, 0,1);
//remove first letter from word
$word = substr($word,1);
//replace first letter with formatted letter
$first = str_replace('{L}',$first,$format);
//add replaced letter to word
$word = $first.$word;
}
//glue words back together and return them
return implode(' ',$words);
}
also before php6 comes out, remember to set these 2 variables in php.ini to better support utf-8
mbstring.func_overload "7"
mbstring.internal_encoding "UTF-8"
精彩评论