php分裂字符串中的2个变量

时间:2012-12-24 20:52:16

标签: php regex

我是编程新手,我正在尝试构建一个小的php价格比较脚本供个人使用。我已经设法解析了一个网站的网站(使用简单的dom解析器),并得到一个(有点)清理过的字符串,其中包含一个层和一个价格。

我正在使用的字符串现在形成如下:

" 50  27,00 "  //50 pieces of a product cost €27,00 (without the ""s)
"1000  26,60 " //1000 pieces of a product cost €26,60

我想将字符串的第一部分抓到$ tier,将第二部分(包括逗号)抓到字符串$ price。

你能帮帮我怎么做吗?有时开始字符串的空格会有所不同(参见上面的示例。中间总是有2个空格。

如果我能像这样(没有空格)的话,数组也没问题:

$pricearray = array(50, "27,00"); //string to number will be my next problem to solve, first things first 

我想我必须使用preg_split,但现在不要使用表达式。

感谢您与我一起思考。

2 个答案:

答案 0 :(得分:4)

最简单的方法是调用explode函数:

$string = '1000 26,60';
$pricearray = explode(' ', $string);

但首先,你必须摆脱所有不必要的空间:

$string = trim($string); // remove spaces at the beginning and at the end
$string = preg_replace('/\s+/', ' ', $string); // replace 1+ spaces with 1 space

空间替换方法取自this question。谢谢,codaddict!

答案 1 :(得分:1)

好吧,正则表达式引擎很难理解,但它们可以轻松地完成这些可选空间。

让我看看我是否在正则表达式中犯了错误:

$yourarray = array();
//just extract the pattern you want
preg_match( '/([0-9]+) + ([0-9]+,[0-9]+)/', " 50  27,00 ", $yourarray );
var_dump( $yourarray );
preg_match( '/([0-9]+) + ([0-9]+,[0-9]+)/', "1000  26,60 ", $yourarray );
var_dump( $yourarray );

// validate and extract the pattern you want
if ( !preg_match_all( '/^ *([0-9]+) +([0-9]+,[0-9]+) *$/', " 50  27,00 ", $yourarray ) )
  print "error";
else
  var_dump( $yourarray );
if ( !preg_match_all( '/^ *([0-9]+) + ([0-9]+,[0-9]+) *$/', "1000  26,60 ", $yourarray ) )
  print "error";
else
  var_dump( $yourarray );
if ( !preg_match_all( '/^ *([0-9]+) + ([0-9]+,[0-9]+) *$/', "1000 26 ", $yourarray ) )
  print "error";
else
  var_dump( $yourarray );