convert decimal value to unicode characters in php - php

i need to convert decimals values into unicode and display the unicode character in PHP.
so for example, 602 will display as this character: ɚ
after referencing this SO question/answer, i was able to piece this together:
echo json_decode('"' . '\u0' . dechex(602) . '"' );
this seems pretty error-prone. is there a better way to do this?
i was unable to get utf8_encode to work since it seemed to want to start with a string, not a decimal.
EDIT: in order to do characters between 230 and 250, double prefixed zeros are required:
echo json_decode('"' . '\u00' . dechex(240) . '"' ); // ð
echo json_decode('"' . '\u00' . dechex(248) . '"' ); // ø
echo json_decode('"' . '\u00' . dechex(230) . '"' ); // æ
in some cases, no zero is required:
echo json_decode('"' . '\u' . dechex(8592) . '"' ); // ←
this seems strange.

While eval is generally to be avoided, it seems strictly-controlled enough to be fine here.
echo eval(sprintf('return "\u{%x}";',$val));

echo json_decode(sprintf('"\u%04x"',$val));
this ultimately worked for me, but i would not have found this without the answer from Niet the Dark Absol

normally, when i attempt to answer my own question, some SO wizard comes along and shows me a built-in function that i should have known about. but until that happens, this is all i can think of:
$leading_zeros = null;
if ( strlen(strval(dechex($val))) >= 4 ) {
$leading_zeros = '';
} else if ( ctype_alpha(dechex($val)[0]) ) {
$leading_zeros = '00';
} else if ( ctype_digit(dechex($val)[0]) ) {
$leading_zeros = '0';
}
echo json_decode('"' . '\u' . $leading_zeros . dechex($val) . '"' );
EDIT: when trying to something similar for javaScript, the documentation tells me the format is supposed to look like "\u####' four digits. i dont know if this is similar to PHP or not.

If you have IntlChar available I'd recommend using IntlChar::chr:
var_dump(IntlChar::chr(602));
Failing that, something like the following avoids any eval/json_decode trickery:
var_dump(iconv('UTF-32BE', 'UTF-8', pack('N', 602)));

Related

php empty string htmlspecialchars()

So, I am trying to use htmlspecialchars() to protect my website but unfortunately I got stuck in this code:
<?php
function wrap_nome($firstname, $lastname)
{
$join = htmlspecialchars($firstname, ENT_QUOTES) . ' ' . htmlspecialchars($lastname, ENT_QUOTES);
if (mb_strlen($join) > 32)
{
$text = substr($join,0,32);
return $text . " ...";
}
else
{
return $join;
}
}
$nome = wrap_nome($firstname, $lastname);
echo '<span style="color:#7F7F7F;font-family:Arial;font-size:13px;"><b>' . $nome . '</b></span>';
?>
Initially I thought that the problem maybe was the fact that the string $nome had double and single quotes, then I removed them and found out that htmlspecialchars($lastname, ENT_QUOTES) continues to be echoed and htmlspecialchars($firstname, ENT_QUOTES) continues to give me an empty string!
If I do this:
echo '<span style="color:#7F7F7F;font-family:Arial;font-size:13px;"><b>' . htmlspecialchars($nome, ENT_QUOTES) . '</b></span>';
... It wont output anything.
Any ideas of what is causing this ?
htmlspecialchars returns FALSE if it gets an error, which happens if $nome contains any characters that can't be represented in the specified character set. The character set defaults to ISO8859-1 before PHP 5.4, UTF-8 since then, try using htmlspecialchars($nome, ENT_QUOTES, 'iso8859-1').
If that doesn't work, see the list of character sets in the documentation and use the appropriate one for your names.
Simply replace
htmlspecialchars($str,ENT_QUOTES );
with
htmlentities($st ,ENT_QUOTES ,"UTF-8");

Get At Least X Characters Before Keyword PHP

I'm making a small search system using php and mysql.
I have this:
preg_match('#(.{75}' . $s . '.{75})#s', $b, $match);
if (isset($match[1])) {
return preg_replace('#(.+?)' . $s . '(.+)#s', '$1<span><b>' . $s . '</b> </span>$2', $match[1]);
} else {
return 'Error';
}
This does a good job of getting the first appearance of the keyword(s) and getting 75 characters before and after it. The only problem is that if there is less than 75 characters, it will not go through. I am pretty new to regex and I actually got help with the above code and it's not fully mine.
If I understood correctly what you want to match any characters from n number up to 75, if that is your case all you have to do is: {10,75} where 10 is the n number(lower) limit in your regex.
'#(.{10,75}' . $s . '.{10,75})#s'

PHP mb_substr not working correctly

I am using Notepad++ to do some HTML and PHP. At one point, I have the following code:
$strUserEmail = $_SESSION["userLoggedIn"];
$strSQL = "SELECT * FROM customer WHERE Email = '$strUserEmail'";
$rsUser = mysql_query($strSQL)
or die($db_name . " : " . $strSQL . " : " . mysql_error());
$rowUser = mysql_fetch_array($rsUser);
$strUserName = $rowUser["FirstName"] . '.' . mb_substr($rowUser["LastName"], 0);
What should come out of that is, for instance, Tom S (Tom being the first name, and S being the first letter of the last name). However, it simply gives me the full last name.
As a second issue, I am using $strUserName to seed a text box in a form following this, but whenever a space is encountered, is ignores the rest as some sort of delimiting value.
You ommited length param in mb_substr() function. Read the doc.
You shouldn't be using mysql_* functions any more as they are deprecated and very unsafe, please learn & use mysqli_* : http://www.php.net/manual/en/book.mysqli.php
Secondly, you have to supply a length to mb_substr, passing the default Null will be interpreted as 0.
try:
$strUserName = $rowUser["FirstName"] . '.' . mb_substr($rowUser["LastName"], 0, 1);
You can also achieve that by using substring method.
$strUserName = $rowUser["FirstName"] . ' ' . substr($rowUser["LastName"], 0, 1);
echo $strUserName;
Edit. Thanks to # czachor making me notice about this.
If you working with unicode charachters, the above function may not work perfectly for you, because the substr() function is not mutli-byte aware. For instance if you are in German, there are umlauts, like Ä,ö ß and so son. So you can better use the mb_substr() like the following.
$strUserName1 = $rowUser["FirstName"]. ' ' . mb_substr($rowUser["ÖLastName"], 0, 1,'UTF-8');
echo utf8_decode($strUserName1);

PHP string replace with characters inbetween tags

I need help with my PHP, I'm using str_ireplace() and I want to filter something out and replace it with what I have.
I find it hard to explain what I am talking about so I will give an example below:
This is what I need
$string = "<error> " . md5(rand(0, 1000)) . time() . " </error> Test:)";
then I want to remove and replace the whole <error> .... </error> with nothing.
So the end outcome should just print 'Test:)'.
Your question is not perfectly clear, but I believe I may understand what you are asking. This code may do the trick:
$string = " " . md5(rand(0, 1000)) . time() . " Test:)";
$newstring = preg_replace("/.*?\ /i", "", $string);
This uses regular expressions to filter out everything that comes before the space (and also removes the space)

Syntax and Variables in PHP

I'm having some trouble with writing some syntax. I want to echo this
'location_1' => $location_1,
However, it is not as simple as it seems. When I write the echo statement the integer 1 must be the variable $z. Here is the code I attempted to write
echo "'location_' . $z . '' =>' . ${'location_' . $z} . ','";
This is what it outputted
'location_' . 1 . '' =>' . something . ','
$location_1 is equal to the string something. I'm lost at how to do this the right way. Any guides on describing how this syntax works would be a major help too so I can understand it completely.
You can just write variables directly into double quoted strings see http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
echo "'location_$z' => \$location_$z,";
You might want to also read the rest of the strings doc
This is the link to the echo documentation (see the examples, I think they described well how it works)
You can break it into two lines and get the expected output.
For example:
$var_location = "$". "location". $z;
echo "'location_" . $z . "' =>'" . $var_location . "','";
One way is: echo "'location_{$z}' => \$location_{$z},";
Edit: Is this what you meant?
<?php
$z = 1;
$location_1 = 'something';
echo "'location_$z' => " . ${'location_'. $z} . ',';
which produces: 'location_1' => something,
Why don't you store these variables inside an array for easier access. Something like:
$locations = array('location_id' => 'location_name');
Here's one way:
echo "'location_$z' => \$location_$z,";
You need to escape the $ symbol. The double quotes represent the thing to echo in this case, whereas the single quotes actually get echoed.

Categories