简体   繁体   中英

Remove string after a certain character?

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.

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'

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.

$str = 'mystring#deletedpartofstring';

$str = preg_replace('/[?#&%=].+/', '', $str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM