How to include the first letter in each word with HTML tags?

How to include the first letter in each word with HTML tags?

For instance:

$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, he needs to work with Unicode UTF-8 ... because I plan to support both Russian and English on this.

+3
source share
5 answers

Try the following:

$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);
}
+7
source

: HTML - , , .. , , HTML .

, , .

$output = preg_replace('!\b([a-zA-Z])!`, '<big>$1</big>`, $input);

(\b), , <big>.

+3

CSS

p { text-transform: capitalize; }

CSS :

  • ; - ,
+2
source

I think you need

preg_replace('~(?<=\p{^L}|^)\p{L}~u', '<big>$0</big>', $input);

note that \ b does not work properly with utf8.

0
source

here is the best and possibly faster version that I just found out myself that supports multibyte utf-8 characters.

in my experience, regular expressions are slow in php, so there is a function based on string manipulation here.

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 release, don't forget to set these 2 variables in php.ini to better support utf-8

mbstring.func_overload "7"
mbstring.internal_encoding "UTF-8"
0
source

Source: https://habr.com/ru/post/1734773/


All Articles