JGeer
JGeer

Reputation: 1852

Remove the & sign using php preg_replace

How can i strip / remove all spaces and & signs of a string in PHP?

I have a string like $string = "this is my string & this also"; the output should be "thisismystringthisalso"

How can I achieve this?

My current code does not replace the & sign:

<?php $string = preg_replace('/\s+/', '', $string);?>

Upvotes: 0

Views: 59

Answers (1)

mvorisek
mvorisek

Reputation: 3418

Try this:

<?php $string = preg_replace('/(\s|&(amp;)?)+/', '', $string);?>

It replaces:

  • white chars (space, tab, ...)
  • "&"
  • "&" html entity (&amp;)

Upvotes: 2

Related Questions