Remove & and Whitespace in URL with preg_replace

2019-07-29 18:11发布

问题:

I am trying to remove Whitespaces and & in a URL and replace it with a -. So far the following works:

preg_replace('/\s+/', '-', $page->label) // whitepace gets replaced with -    
preg_replace('/\&/', '-', $page->label) // & gets replaced with - 

I would like to have this in one line, but I am not able to combine the 2. Can anyone help? Thank you very much in advance.

回答1:

This should keep it all nicely in one line.

$output = preg_replace('/\s+|&/', '-', $page->label);


回答2:

 $test = preg_replace('/\s+/', '-', $page->label);  
 $final_output = preg_replace('/\&/', '-', $test); 

Try like this



回答3:

preg_replace( '/[&]|\s+/', '-', $page->label );


回答4:

$output = preg_replace('/([\s+|\&])/', '-', $page->label);


回答5:

if you use Zend Framework, maybe Zend View Escaspe is better.