use regex or php function to get all characters before ":" (colon)
I have many fields that are like this pattern:
re2man: (johnny bravo)
re1man: (john smith)......
user: (firstname lastname)..
I wanted to use regex, or another php function to get only characters before the colon (开发者_运维问答":")
Look at explode()
to simply split the string at the ':'.
For instance, list($username) = explode(':', $string);
(list()
is being used to assign just the first part of the exploded string to $username
and discard the rest; a longer way to do it would be:
$parts = explode(':', $string); $username = $parts[0];
Also, you could use the extra limit parameter to indicate that you don't need the rest of the parts, like:
list($username) = explode(':', $string, 1);
That may or may not be faster. Also, I would expect using explode()
to be more efficient than some of the other regex-based solutions offered.
Regex style:
preg_match('/([^:]*):/', $subject, $matches);
Plain string searching:
strstr($subject, ':', true);
Use print preg_replace('/^([^:]+)(:.*)$/', "$1", $string);
How about this:
$matches = array();
preg_match('/([\w\d]+):\s+\(([\w\d\s]*\))/', $line, $matches);
$username = $matches[1];
$realname = $matches[2];
Of course, you should loop around this, and also check the return value of the preg_match()
call to see if the line matched your expectations.
精彩评论