Archivi tag: str_replace en dash

Str_replace that En Dash (or minus sign)! How to fix the problem when it’s not working

Building my first theme on WordPress I had been a very long time in to understand how to use str_replace function to change title of a page to remove all the words following another. This was approximately the string to change: i had name and surname of a specific person (John Doe) and what i wanted to do was to remove all the rest of the phrase.

Page Title:  John Doe Contact Page – Sitename

String i wanted to get as result after str_replace:  John Doe

So practically i had to get just “John Doe” from that page title. The easiest way i knew was to use str_replace function in PHP in the following way:

  • Getting the WordPress Title as a variable:


$string = get_the_title();
$replace = ” Contact Page – Sitename”;
$replacewith   = ” “;


  • Then using str_replace to change the title and print the result:


$string = str_replace($replace, $replacewith, $string);


Unfortunately first attempts didn’t working and the result i got was just the input string ($string) without any replacement. Then i just cruised on the internet and after failed attempts to understand why i didn’t get my hoped result I decided to try to remove just the last word of the input string to check str_replace function was actually working.

Input:  John Doe Contact Page – Sitename

String i wanted to get as result after str_replace:  John Doe Contact Page –

Well, it worked. So i realized that probably the issue was that dash in the middle of the title. To be honest I did not know it was called “dash”, I just used to call it “minus” and type it very simply using these keyword keys:

But, it was so. And i found there’s not just one dash but as many as 5 different types, two of which very very similar to each other. Wikipedia explain fairly clearly the difference between them.

So, you can figure out that figure dash and en dash are pretty similar each other, and they are also different from the minus sign (-) of the keyboard. Opening page source in the browser I got confirmation that in my case it was a endash, then sign was not show as itself but with HTML/XML numeric character reference &#8211; from which i could understand what it was.

At this point I repeated the str_replace on my string just not using the sign but the appropriate HTML/XML code (previously I was using “minus” sign).

This was the page title as well as it appeared on the browser:
John Doe Contact Page – Sitename

This was my wrong way to write it:
John Doe Contact Page – Sitename

The properly way to str_replace an endash sign:
John Doe Contact Page &#8211; Sitename