开发者

How to grab certain string from another string using php?

I have a st开发者_如何学Pythonring like "You can win tonight $200,000. Sign up now!"

Where the prize is changing from string to string, so I have to do it somehow using php regex or somthing like that.

How to get just this value from this string using php?

Is there a simple regex function?

Thanks in advance.


You're looking for preg_match, I think:

 preg_match("/\$[\d\,]+/", "You can win tonight $200,000. Sign up now!", $matches);
 # $matches[0] will be "$200.000"

Breaking it down:
The regular expression look for a dollar sign (which has special meaning in regular expressions, so we escape it with backslash, so it's taken as literal dollar sign), followed by 1 or more digits (0-9) and commas.

Note that if preg_match itself returns false, it's because the string didn't match the regexp, and in that case, there will be no $match[0] to read


There are two ways I can see to do this, you can use regular expressions (slower) or explode (faster, but less accurate). The advantage is that if someone removes spaces from the string the RegEx will still work while explode may suddenly break.

$src = "You can win tonight $200,000. Sign up now!";
function get_amount($from){
  $src_tkns = explode(' ', $from);
  foreach($src_tkns as $tkn){
    if(substr($tkn, 0, 1)==='$'){
      return (substr($tkn, -1, 1)=='.')?substr($tkn, 0, -1):$tkn;
    }
  }
  return false;
}

function get_amount_regex($from){
  $r = '/\$[-+]?[0-9]*(\,?[0-9]+)+/';
  preg_match_all($r, $from, $res);
  return is_array($res)?$res[0][0]:false;
}

print('Found: '.get_amount($src).'<br />');
print('Regex Found: '.get_amount_regex($src));

More about regular expressions and their usage on the PHP PCRE page at http://www.php.net/manual/en/book.pcre.php and on the Regular Expressions info site at http://www.regular-expressions.info/tutorial.html

One thing to note, the code above isn't optimal or all catching when it comes to errors. Make sure you perform tests with known valid and invalid strings before you use it for some type of critical work :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜