Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using substr() in multiple languages including arabic language with php

Tags:

php

substr

arabic

I know there are a lot of questions already posted with arabic language in php, but I was unable to get solution to my problem and hence I am posting this question:

I have a PhP site that is running perfectly in English language. Now, I want it to support multiple languages including French, Spanish, Arabic but I am unable to use them with one code. The problem is, I have used substr() in many places and the translated characters not work as intended with substr(). I also tried with mb_substsr(), but of no use :(

The field in DB is "utf8_general_ci" and I have already placed header('Content-type: text/html; charset=UTF-8'); in my code to allow rendering in UTF-8.

The problem is either I get "?????" in place of the exact words or I get incorrect words with substr()

Please help!!

like image 281
Nitesh Avatar asked Jun 25 '11 18:06

Nitesh


2 Answers

For Arabic word: I want get the character in position 2 only.

$name = "MYNAME";
$Char = substr($Name,2,2);
echo $Char; // print N this okay.

But for Arabic work like كامل, it returns question mark

case 1: $Char = substr($Name,0,1);     // Not Work and return question mark
case 2: $Char = substr($Name,1,1);     // Not Work and return question mark
case 3: $Char = substr($Name,0*2,1*2); // Work and return "ك"
case 3: $Char = substr($Name,1*2,1*2); // Work and return "ا"

So I find the solution:

$Char = mb_substr($Name,1,1,'utf-8');  // Work and return "ا".
like image 97
Moe Avatar answered Nov 20 '22 00:11

Moe


First of all, forget substr. If you are going to encode your strings in UTF-8 and splitting them up, then mb_substr is the only working solution.

You also need to make sure that the connection encoding of MySql is also UTF-8. Do this by calling

mysql_set_charset('utf8');

just after mysql_connect. There are equivalent ways to do this if you are using a data access layer other than the mysql extension (such as PDO).

like image 34
Jon Avatar answered Nov 20 '22 01:11

Jon