Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first character of a string, that is a French accent [duplicate]

Tags:

css

php

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.

like image 294
Etdashou Avatar asked Apr 19 '13 22:04

Etdashou


3 Answers

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)

like image 171
bwoebi Avatar answered Nov 02 '22 06:11

bwoebi


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.

like image 1
Esailija Avatar answered Nov 02 '22 05:11

Esailija


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 }
like image 1
Clarence Avatar answered Nov 02 '22 05:11

Clarence