问题
I want to substring the text, ex. "Hello - How are you?" by using this code
$text= "Hello - How are you?";
$strings = explode(' - ',$text);
echo $strings[0]; // Hello
echo $strings[1]; // How are you
it will not work, because of ' - '.
If i change to:
$text= "Hello-How are you?";
$strings = explode('-',$text);
echo $strings[0]; // Hello
echo $strings[1]; // How are you
it's ok.
Can someone help me? Thank you.
回答1:
I had the same problem, after an hour of investigating, turns out that texts copied from Microsoft Word have such a problem, word chooses to convert the minus character ( - ) to en dash ( – ) here you can see them side by side to see the difference: -–
I don't know why word does that, but we are used to see such annoying things done by word and you should never let anyone copy a text from word to you application!
To make you code work in these conditions you must first replace these odd characters:
$text= "Hello-How are you?";
$strings = str_replace('–', '-', $text);
$strings = explode('-',$text);
echo $strings[0]; // Hello
echo $strings[1]; // How are you
回答2:
I find out another way:
$title= filter_var($title, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$title= str_replace('–', '-', $title);
$size = explode('-', $title);
Anything else works for me
回答3:
Chances are, your "spaces" are not real spaces but rather tabs or similar, and the hypen could be one different from the standard one, for example —
or –
instead of -
.
You could then try the following:
$strings = preg_split('/\s[—–-]\s/', $text);
to properly split that string.
来源:https://stackoverflow.com/questions/18688287/php-explode-not-work-with-character