Search code examples
phpstringspecial-characters

check if the string begin with euro/pound symbol


I'm trying to check if a string is start with '€' or '£' in PHP.

Below are the codes

    $text = "€123";

    if($text[0] == "€"){
        echo "true";
    }
    else{
        echo "false";
    }

    //output false

If only check a single char, it works fine

    $symbol = "€";

    if($symbol == "€"){
        echo "true";
    }
    else{
        echo "false";
    }
    // output true

I have also tried to print the string on browser.

$text = "€123";
echo $text; //display euro symbol correctly
echo $text[0] //get a question mark 

I have tried to use substr(), but the same problem occurred.


Solution

  • Characters, such as '€' or '£' are multi-byte characters. There is an excellent article that you can read here. According to the PHP docs, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

    Also make sure your file is encoded with UTF-8: you can use a text editor such as NotePad++ to convert it.

    If I reduce the PHP to this, it works, the key being to use mb_substr:

    <?php
      header ('Content-type: text/html; charset=utf-8');
      $text = "€123";
      echo mb_substr($text,0,1,'UTF-8');
    ?>
    

    Finally, it would be a good idea to add the UTF-8 meta-tag in your head tag:

    <meta charset="utf-8">