stefanosn
stefanosn

Reputation: 3324

str_replace not working on strange character

I get this string "Holder – 2pcs" from my Wordpress post title using the get_the_title() function then I use str_replace to replace the "–" character but no luck!

str_replace("–","-","Holder – 2pcs");

any help appreciated!

Edit:

(Response to comments)

I had to save the text from $title1=get_the_title(); to .txt file and I noticed that the – saved as – in the txt file ... then I replaced str_replace("–","-","Holder – 2pcs") and it works! the problem is that in my wordpress databse the title contains - char as it should but then when I use get_the_title(); function of wordpress in my code to retrieve the title I get the - char as – which is eventually – I dont know why get_the_title(); causing this issue!

Any thoughts?

Upvotes: 0

Views: 1545

Answers (2)

Martin
Martin

Reputation: 22760

Your issue is caused by your "-" character being something else that looks the same.

Step 1:

Ensure that everything is using the same Character set, from your MySQL to your PHP to your input text.

$title1 = iconv(mb_detect_encoding(get_the_title(), mb_detect_order(), true), "UTF-8", get_the_title());

(reference)

Step 2:

Ensure that what you convert is the raw string and not an HTML encoded output

$title2 = html_entity_decode($title1, ENT_NOQUOTES | ENT_HTML5, "UTF-8");

Step 3:

Run the str_replace() function as originally attempted. If there are a range of possible "dash" characters then you can build an array:

$dashes = ['–','–','—','-'];
$title3 = str_replace($dashes,"-",$title2);

(reference)

Upvotes: 1

Álvaro González
Álvaro González

Reputation: 146410

The code you've shared does work:

var_dump(str_replace("–","-","Holder – 2pcs"));

string(13) "Holder - 2pcs"

If it doesn't, they you're actually running something different. Most likely, your input data contains white space or HTML entities and you're looking at it through browser glasses.

Trying further inspecting your input data with e.g.:

header('Content-Type', 'text/plain');
var_dump("Holder – 2pcs", bin2hex("Holder – 2pcs"));
string(15) "Holder – 2pcs"
string(30) "486f6c64657220e280932032706373"

Upvotes: 0

Related Questions