Take the 2-minute tour ×

How can I remove the remaining part of a string after certain characters like ?, #, &, %, = in PHP? Any ideas? I tried preg_replace(), but I couldn't figure it out.

share|improve this question

3 Answers 3

Update, just realized I read it wrong. You're looking for stuff before, not after. Updated code:

$test_string = 'remember?forget';
preg_match('/([^?#&%=]+)/', $test_string, $matches);
$part_before_char = $matches[1];

After run, $part_before_char = 'remember'

share|improve this answer
$str = 'mystring#deletedpartofstring';

$str = preg_replace('/[?#&%=].+/', '', $str);
share|improve this answer
you got the right idea, but the code didn't work –  user962449 Dec 5 '12 at 23:54
it worked on my host..... –  Sergio Toledo Piza Dec 5 '12 at 23:56
why was it down voted? :/ –  user962449 Dec 5 '12 at 23:58
Removed downvote. But character classes don't need vertical bars. Things in character classes are OR'd by default. –  Brian Cray Dec 6 '12 at 0:04
ooh yes, I forgot this, so, I removed the vertical bars now –  Sergio Toledo Piza Dec 6 '12 at 0:09

This should work:

$str = "Hello World#somesuffixstr";
preg_match("/^(.*?[?#&%=]).*/", $str, $str);
echo $str[1];
// Should output "Hello World#"

About the regex pattern:
It searches for beginning of string (^), then for any character 0 or more times (which is group #1), then such a symbol like & or %, then any character zero or more times. It replaces the string with the characters matched in group #1.

share|improve this answer

Your Answer


