'Explode not working properly with dash
We have this string : "Il Responsabile della Sicurezza nelle gallerie – 1° PARTE" and we want to get two part of it:
- Il Responsabile della Sicurezza nelle gallerie
- 1° PARTE
We are not able to get them using explode()
on – char
We have already seen this but neither of each answer worked for us.
We have tried at frontend with javascript but with not positive results.
How can we fix it? Could it be an issue of charsted? (currently ISO-859-1 and we cannot change it)
Solution 1:[1]
There is "atypical" dash symbol in your string, it's called Unicode Character 'EN DASH' (U+2013).
Replace it with it's utf-8 equivalent, then, you'll able to easily split the string:
$str = "Il Responsabile della Sicurezza nelle gallerie – 1° PARTE";
$endash = html_entity_decode('–', ENT_COMPAT, 'UTF-8');
$str = str_replace($endash, '-', $str);
print_r(explode("-",$str));
The output:
Array
(
[0] => Il Responsabile della Sicurezza nelle gallerie
[1] => 1° PARTE
)
Solution 2:[2]
The character you are exploding with is not dash.
Copy and paste the character and then try.
Corrected Code:
<?php
$str = 'Il Responsabile della Sicurezza nelle gallerie – 1° PARTE';
$arr = explode('–', $str);
echo '<pre>';print_r($arr);echo '</pre>';
?>
Output I am getting:
Array
(
[0] => Il Responsabile della Sicurezza nelle gallerie
[1] => 1° PARTE
)
Solution 3:[3]
I tried all your solutions and all of them worked partially in my query from the DB, so, I tried using all of them in a function
I hope this could help to get a better and global solution.
The function will check if the exploded worked and the vector has more than index zero. If is not there, it will try another method for checking the simbol
function get_separated_title($post_title) {
$repared = str_replace('-', '-', $post_title);
$titulo = explode("-", $repared);
if (!isset($titulo[1])) {
$raw = filter_var($post_title, FILTER_SANITIZE_STRING);
$repared = str_replace('–', '-', $raw);
$titulo = explode("-", $repared);
if (!isset($titulo[1])) {
mb_internal_encoding("UTF-8");
$endash = html_entity_decode('–', ENT_COMPAT, 'UTF-8');
$repared = str_replace($endash, '-', $raw);
$titulo = explode("-", $repared);
}
}
return $titulo;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | RomanPerekhrest |
Solution 2 | Pupil |
Solution 3 | Gendrith |