Forum Moderators: coopster
How can I reduce this:
str_replace('/','',str_replace('-','',str_replace('&','',str_replace(')','',str_replace('(','',str_replace('"','',str_replace('.','',str_replace('!','',str_replace('?','',str_replace(' ',' ',str_replace(', ',', and ',str_replace(' ',', ',$title),-1)))))))))))
Thanks heaps
$badchars = array('/', '-', '&', ')', '(', '"', '.', '!', '?');
str_replace($badchars,'',$title);
str_replace(', ',', and ',$title);
that is much easier to read.
you seem to be replacing a space with a space in there, I skipped that. You also are replacing spaces with comma space, not too sure about that one either, I left it out.
It's actually become a bit longer :)
$title=str_replace(':','', str_replace(';','', str_replace('/','', str_replace('-','', str_replace('&','', str_replace(')','', str_replace('(','', str_replace('"','', str_replace('.','', str_replace('!','', str_replace('?','', str_replace(' ',' ', str_replace(' ',', ',trim($title))))))))))))))
I replace two spaces with one and space with comma space
Any ideas how I could use preg to do this?
[edited by: jatar_k at 2:38 pm (utc) on May 28, 2007]
[edit reason] fixed sidescroll [/edit]
[php.net...]
I still don't get why you replace every space with comma space, but that's just me ;)
it is a bit longer but much more readable
are you cleaning user submitted data?
Try:
$before ='This is a sentence )*(a(B*Z&abc%QER12356';
$after = preg_replace( '/[^a-zA-Z]/', '', $before);
echo $before.'<br />'.$after.'<br />';
to get
This is a sentence )*(a(B*Z&abc%QER12356
ThisisasentenceaBZabcQER
or add a space to the pattern to keep the spacing between the words
$after = preg_replace( '/[^a-zA-Z ]/', '', $before);
echo $before.'<br />'.$after.'<br />';
to get
This is a sentence )*(a(B*Z&abc%QER12356
This is a sentence aBZabcQER
PS
For what you are doing, if you KNOW the strings you want to eliminate, str_repl executes faster.
[edited by: CDNQuilter at 6:00 pm (utc) on May 28, 2007]
Awesome! Works great!
Thank you so much!
I have one more question that you may be able to help me with:
My string may look like this:
word1, word2, word3, word4
I would like to make this:
word1, word2, word3 and word4
so the LAST comma in the string has to be swapped to " and "
I tried things like str_replace (', ', ' and ', $subject, -1) but this does not seem to work (maybe because I have PHP4)
Any ideas?
Thanks again for the preg help - now that I see it it makes more sense.
[edited by: Roel at 1:38 am (utc) on June 4, 2007]