php:使用prematch模式拆分字符串

时间:2016-09-16 19:17:30

标签: php preg-match-all

我想在数组中拆分字符串,如下例所示: 这些值来自foreach循环

array('11222S','11222M','11222');

我需要以下输出:

Array
(
    [0] => Array
        (
            [0] => 11222
            [1] => S
        )

)

Array
(
    [0] => Array
        (
            [0] => 11222
            [1] => M
        )

)

Array
(
    [0] => Array
        (
            [0] => 11222
            [1] => 
        )

)

请帮我分解一下。

我在下面尝试但没有得到结果: -

preg_match_all('!\d+!', $value, $matches);

3 个答案:

答案 0 :(得分:1)

您可以使用preg_match切换每个字符串,而不是使用preg_split,而不是使用$arr = ['11222S', '11222M', '11222']; $res = array_map(function ($i) { return preg_split('~(?!\d)~', $i, 2); }, $arr);

 class Program
    {
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            try
            {
                Console.WriteLine(String.Format("Inicio webjob:  {0}", DateTime.Now.ToString()));

                JobHostConfiguration config = new JobHostConfiguration();
                config.Tracing.ConsoleLevel = TraceLevel.Verbose;
                config.UseTimers();
                JobHost host = new JobHost(config);
                host.RunAndBlock();

                Console.WriteLine(String.Format("Fin webjob:  {0}", DateTime.Now.ToString()));

            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error webjob:  {0}", ex.Message));
                Console.WriteLine(String.Format("Error webjob:  {0}", ex.StackTrace));
                //throw ex;
            }

        }
    }




  public class Functions
    {

        public static void CronJob([TimerTrigger("0 */1 * * * *")] TimerInfo timer)
        {
            try
            {
                Console.WriteLine(String.Format("Inicio lectura mensajes : {0}", DateTime.Now.ToString()));
                string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                                       Configuracion.StorageAccountName, Configuracion.
                                       StorageAccountKey);
                string _guid = Guid.NewGuid().ToString();
                string eventProcessorHostName = _guid;
                EventProcessorHost eventProcessorHost = new EventProcessorHost(
                                                                eventProcessorHostName,
                                                                Configuracion.EventHubName,
                                                                EventHubConsumerGroup.DefaultGroupName,
                                                                Configuracion.EventHubConnectionString,
                                                                storageConnectionString);
                Console.WriteLine("Registering EventProcessor...");
                var options = new EventProcessorOptions();
                options.ExceptionReceived += (sender, e) => { Console.WriteLine(e.Exception); };
                eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>(options).Wait();
                //Console.WriteLine("Receiving.Press enter key to stop worker.");
                //Console.ReadLine();
                eventProcessorHost.UnregisterEventProcessorAsync().Wait();
                Console.WriteLine(String.Format("Fin lectura mensajes : {0}", DateTime.Now.ToString()));
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }
    }

答案 1 :(得分:0)

模式可以改变,所以试试这个:

$startArray = array('11222S', '11222M', '11222');//but pattern can change
$count = count($startArray);    

$master_array = array(); //hold the split values

for($i = 0; $i < $count; $i++) {

    $numericPiece = preg_replace("/\D*/", "", $startArray[$i]);
    $alphaPiece = preg_replace("/\d*/", "", $startArray[$i]);

    $master_array[] = array($numericPiece, $alphaPiece);

}

答案 2 :(得分:0)

  

您可以尝试foreach()preg_replace()的组合,如下所示。您也可以Quick-Test it Here

<?php
    $array          = [
                        "11222STV",
                        "11222M",
                        "18742KUM",
                        "11222",
    ];
    $splitArray     = [];
    foreach($array as $k=>$v){
        $tmp            = [];
        $number         = (int)preg_replace("#([A-Z]*?)#",  "", $v);
        $char           = preg_replace("#(\d*?)#",          "", $v);
        $tmp[]          = ($number) ? $number   : "";
        $tmp[]          = ($char)   ? $char     : "";
        $splitArray[]   = $tmp;
    }

    var_dump($splitArray);
  

以上var_dump()会产生:

    array (size=4)
      0 => 
        array (size=2)
          0 => int 11222
          1 => string 'STV' (length=3)
      1 => 
        array (size=2)
          0 => int 11222
          1 => string 'M' (length=1)
      2 => 
        array (size=2)
          0 => int 18742
          1 => string 'KUM' (length=3)
      3 => 
        array (size=2)
          0 => int 11222
          1 => string '' (length=0)