Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace or strip out ndash character from a string?

Tags:

php

The problem looks simple, but it's taking time to figure out. I need to get rid of ndash characters from some strings in a project. Not the HTML entity –, but the actual character ( ). Using str_replace() and preg_replace() didn't work.

Already tried:

$new_str = str_replace('–', '', $str_with_ndash_char);     

Also tried:

$new_str = preg_replace('/–/', '', $str_with_ndash_char);  

Also, it's a legacy project. Some parts of it are iso-8859-1 encoded, and a few others are utf-8 encoded. I noticed that my editor (Komodo Edit) complains about the ndash character when a PHP file is iso-8859-1, losing the character when I save the file, like this:

$new_str = str_replace('?', '', $str_with_ndash_char);

Converting everything to utf-8 results in a lot of garbage characters (same for the other way around, converting everything to iso-8859-1), so I'm avoiding doing it unless it's really, really necessary.

Edited: removed double $ signs (bad CTRL+V).

like image 698
Emerson Avatar asked Dec 10 '25 01:12

Emerson


2 Answers

I just tried out what you are doing and worked just fine, make sure that is is n-dashed in the string and not em-dashes.

I tried replacing both the different types and found no issues.

$str = str_replace('—', '', '–test—');   
echo $str . '</br>';
$str = str_replace('–', '', $str);     
echo $str;

This gives me the result:

-test
test

Some more concrete example would be nice as well. Like the strings you are trying to change and not just the variables.

like image 158
Tobias Avatar answered Dec 11 '25 18:12

Tobias


It seems that error is in redundant $ sign. It should be exactly one dollar sign in a variable.
So the line $new_str = str_replace('–', '', $str_with_ndash_char); should work fine.

But if it all OK in code in your project, the you should check out this answer

Also, try to switch error reportin mode to E_ALL. Place error_reporting(E_ALL); on the top of your script

like image 42
Nestor Yanchuk Avatar answered Dec 11 '25 16:12

Nestor Yanchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!