【问题标题】:How could I split value in php?如何在 php 中拆分值?
【发布时间】:2016-03-02 08:18:07
【问题描述】:

我在 PHP 文件中有这样的值:

{First=itema,Fourth=10000.0,Second=10,Third=1000},{First=itemb,Fourth=12000.0,Second=12,Third=1000}

我怎样才能拆分这些值直到我得到这样的值:

{itema,10000,10,100} AND {itemb,12000,12,1000}

我从我的 android 应用程序中的方法 POST 中获得了该值,然后我进入了我的 PHP 文件,如下所示:

<?php


$str = str_replace(array('[',']'), '', $_POST['value1']);
$str = preg_replace('/\s+/', '', $str);

echo $str;

?>

而且,这是我在 android 应用程序中的代码:

try {

            httpclient = new DefaultHttpClient();
            httppost = new HttpPost("http://192.168.107.87/final-sis/order.php");

            nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("value1", list.toString()));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response=httpclient.execute(httppost);
            Log.d("Value Price: ", httppost.toString());
            HttpEntity entity=response.getEntity();
            feedback = EntityUtils.toString(entity).trim();
            Log.d("FeedBack", feedback);

        }catch (Exception e){

        }

这是关于我的代码的完整链接:

How can I store my ArrayList values to MySQL databases??

我之前一直在问,但我找不到最好的方法。

谢谢。

【问题讨论】:

  • 只需使用正则表达式即可
  • 向我们展示您迄今为止的尝试?
  • 这是字符串还是数组?
  • 我试过这样:$str = str_replace(array('[',']'), '', $_POST['value1']); $str = preg_replace('/\s+/', '', $str); $value1 = preg_split("/[,]+/", $str);@FakhruddinUjjainwala
  • 我从我的 android 应用程序中将其发布为数组列表 @WilliamJanoti

标签: php arrays split


【解决方案1】:

这将产生所需的字符串。我首先使用一些正则表达式来拆分初始字符串,然后获取每个值。

$s = '{First=itema,Fourth=10000.0,Second=10,Third=1000},{First=itemb,Fourth=12000.0,Second=12,Third=1000}';

preg_match_all('/\{[^}]*}/', $s, $m);

此时$m包含:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(49) "{First=itema,Fourth=10000.0,Second=10,Third=1000}"
    [1]=>
    string(49) "{First=itemb,Fourth=12000.0,Second=12,Third=1000}"
  }
}

然后我们循环每个部分。下一个正则表达式:

'/\=([^\,]+)/'

这就是说,抓取等号和逗号之间的所有文本并将其放入捕获组。

然后我们就将匹配内爆。

$parts = array();
foreach($m[0] as $match) {
   $t = trim($match, '{}');
   preg_match_all('/\=([^\,]+)/', $t, $m2);
   $parts[] = '{'.implode($m2[1], ',').'}';
}

$finalString = implode($parts, ' AND ');
var_dump($finalString);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2013-08-09
    相关资源
    最近更新 更多