How can I reindex a string?
It basically comes down to this. I have a string called $name. $name usually has the value ''blablabla'', the value comes from an external resource so that's why it's encapsulated in two single quotes. If i would declare this variable myself it would look like this:
$name = "''blablabla''";
I am deleting these single quotes by:
$name[0] = '';
$name[1] = '';
$name[mb_strlen($name, 'UTF-8')-1] = '';
$name[mb_strlen($name, 'UTF-8')-2] = '';
(unsetting the string with a index doesn't work) So now I h开发者_如何学JAVAave $name with value "blablabla" without the signle quotes. Here's my problem. When I look at the source code, there are strange characters before the "blablabla". How can I deal with this? And, is there any way to reindex my string (for example what array_values does for arrays)?
EDIT Eventually I used this code :
$name = mb_substr($name, 2, -2, 'UTF-8');
$name = "''foo''";
$name = substr($name, 2, -2);
echo $name; # foo
- You're dealing with encodings, while the characters in question (
'
) are single-byte. Strings in PHP are still binary only, which means, you can just cut it off at the ends. - When you unset using the index, keep in mind that it's the binary position.
mb_strlen
does not suit to gather the binary index position,strlen
does:
.
$name = "''foo''";
$name[0] = '';
$name[1] = '';
$len = strlen($name); # binary safe string length
$name[$len-1] = '';
$name[$len-2] = '';
echo $name; # foo
mb_strlen
compared with strlen
$utf8 = 'ä';
mb_strlen($utf8, 'UTF-8'); # 1
strlen($utf8); # 2
$utf8[1] != 'ä';
You could use the Trim function:
$name = trim($name, "'");
echo $name; // Prints: blablabla
精彩评论