I have a strange problem and I am not sure how to resolve it. I would like to get the first character of a Text field I get from a Database. With this character, I would apply a CSS style to make it big.
If you try this following code, you will understand what is my problem:
<?php
$str_en = "I am a sentence.";
echo $str_en[0];
echo "<br /><br />";
$str_fr = "À tous les jours je fais du PHP.";
echo $str_fr[0];
echo "<br /><br />";
$str_fr = "Étais-tu ici?";
echo $str_fr[0];
?>
The code Above will output:
I
Ã
Ã
It seems like that a French character is using more than one bytes in a string. The problem is that not all my sentence start with a French character. Anyone have an idea how I could have a function that convert this:
<?php
$str_fr = "Étais-tu ici?";
?>
To this
$str_fr = "<span class='firstletter'>É</span>tais-tu ici?";
Or perhaps there is a better way with CSS3 to do this.
See for mb_substr
(http://www.php.net/manual/en/function.mb-substr.php)
$first_char = mb_substr($string, 0, 1, 'utf-8'); // You may change the forth parameter according to your needed encoding.
mb_substr
repects the encoding and returns all the bytes representing the first character here.
CSS3 has a pseudo-class ::first-letter
which selects only the first letter.
Example:
Your HTML is:
<p id="french_text">Étais-tu ici?</p>
Then you can address it with CSS3 by:
p:first-letter { /* Your properties */ }
(P.s.: Nowadays' standard is using ::first-letter
(double double colon instead of a single double colon), but for best backwards compability use only one double colon)
The output should have been:
I
�
�
You can fix that by doing
<?php
header("Content-Type: text/html; charset=utf-8");
Currently your source is in UTF-8 but browser interprets it as Windows-1252.
You can then do $first_char = mb_substr($string, 0, 1, "UTF-8");
to complete your problem.
You better apply the :first-letter pseudo class to the container element. It's supported by all major browsers and does not mess up your HTML. For instance if you have a list with items as:
<ul>
<li>First db term</li>
<li>Second db term</li>
</ul>
You apply the first-letter CSS to each li element as:
ul li:first-letter { font-size: 3em }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With