Possible Duplicates:
PHP Regex to convert text before colon to link Return the portion of a string before the first occurrence of a character in PHP
I need to get the username from a Twitter RSS feed.
I am returning this data from the feed as the title, and I want to extract the username.
UsernameIwanttoget:This is the Twitter message....
So basically, get all the text before :
.
$pos = strpos($text, ':');
if ($pos !== false) {
$username = substr($text, 0, $pos);
$message = substr($text, $pos + 1);
}
You don't really need regular expressions here. Regular expressions are slow and not easily understandable if you're not familiar with them, so you'd better go with a string function when you can.
You should use cdhowie's answer instead.
I'd do this with explode()
:
$pieces = explode(':', $text, 2);
if (count($pieces) != 2) {
# Malformed message
}
$username = $pieces[0];
$message = $pieces[1];
If you want the message too, extracting both pieces at once this way is (IMO) a bit more readable than using a regular expression or substr
.
If there is optional whitespace padding, you might consider running the result strings through trim()
.
explode() would be better. You can then make use of both the username and tweet.
$tweet = explode(":", $text);
$text[0]
will give you the username, and $text[1]
would give you the tweet.
You don't need a regular expression for such a simple task. Just search for the colon and extract the characters up so far:
$str = 'UsernameIwanttoget:This is the twitter message...';
$pos = strpos($str, ':');
if (!$pos)
{
// Something went wrong: $str doesn't have the expected format!
}
else
{
$username = substr($str, 0, $pos);
}
You could also use the explode() function.
Example:
$stuffIWant = "UsernameIwanttoget:This is the Twitter message....";
$pieces = explode(":", $stuffIWant);
echo $pieces[0]; // piece1
Use:
preg_match("/([a-zA-Z0-9\\-]*)(\\s)*:/", $string, $result);
This will get you all alphanumeric characters (and the dash), but it will not match any spaces between the text and the ":"
So $result[1]
will have the matched string.
What yokoloko and Flinsch said is true, but for the answer's sake:
$str = 'UsernameIwanttoget:This is the Twitter message...';
preg_match('/([A-Z0-9]+)[^\s]:/i', $str, $matches);
// If something could be matched, $matches[1] contains the matched part
$username = $matches[1];
//etc...
精彩评论