Skip to content

Instantly share code, notes, and snippets.

@ahmadazimi
Last active April 23, 2025 08:54
Show Gist options
  • Select an option

  • Save ahmadazimi/b1f1b8f626d73728f7aa to your computer and use it in GitHub Desktop.

Select an option

Save ahmadazimi/b1f1b8f626d73728f7aa to your computer and use it in GitHub Desktop.
PHP replace Zero Width Space using preg_replace
<?php
/**
* http://stackoverflow.com/questions/11305797/remove-zero-width-space-characters-from-a-javascript-string
* U+200B zero width space
* U+200C zero width non-joiner Unicode code point
* U+200D zero width joiner Unicode code point
* U+FEFF zero width no-break space Unicode code point
*/
$text = preg_replace( '/[\x{200B}-\x{200D}]/u', '', $text );
@cc9999

cc9999 commented Sep 5, 2016

Copy link
Copy Markdown

thanks!

@edgarshurtado

Copy link
Copy Markdown

Awesome! How useful a single line of code has been. Thank you, it was what I needed!

@firestorm23

Copy link
Copy Markdown

Does not removes U+FEFF, if you use exact range shown in sample code.
You need to include it explicitly, out of character class.

$text = preg_replace( '/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $text );

@aolin480

aolin480 commented Jun 21, 2018

Copy link
Copy Markdown

Using @firestorm23 solution along with the gist worked for me. You can test it out by selecting the text here -> and running it through the preg_replace using firestorm23's solution

https://r12a.github.io/uniview/?charlist=*%2F%20%EF%BB%BF%40#title

$text = '*/ @';
$text = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $text);

Github will probably strip the zero-width character in this comment in the $text variable, just copy the text from link above

@Benyaminrmb

Copy link
Copy Markdown

Does not removes U+FEFF, if you use exact range shown in sample code.
You need to include it explicitly, out of character class.

$text = preg_replace( '/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $text );

@looper200

Copy link
Copy Markdown

Thank you That works
$text = preg_replace( '/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $text );

@ladyra

ladyra commented Nov 26, 2021

Copy link
Copy Markdown

Thanks a lot, this was really helpful :)

@jgregory78

Copy link
Copy Markdown

THANK YOU!!!! I'm late to the party, but this really helped me out today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment