分离数据并将它们放在一个数组(PHP)中


Separate data and put them in an array (PHP)

我有一个名为$name的变量,它包含如下内容:

$name = 'FName_LName_DataX_Number_www.website.com';

我想把Number之前的所有数据放在一个不带下划线和Number值的数组中。

类似这样的东西:

$array[0] = 'Fname Lname DataX';
$array[1] = 'Number';

$name示例:

$name = 'Roberto_Carlos_01_www.website.com';
$name = 'TV_Show_Name_785_www.website.com';

使用正则表达式是一个特殊的问题。但在任何时候,有人给出了这种解决方案,另一个人说regular expressions are evil!。让我们玩一点:

$index  = 0;
$array  = array();
$array0 = array();
$array1 = array();
$name = 'FName_LName_DataX_002_www.website.com';
$aux = explode('_', $name);
if (is_array($aux))
{
    foreach ($aux as $key => $value)
    {
        if (is_numeric($value))
        {
            $index = $key;
            break;
        }
    }
    foreach ($aux as $key => $value)
    {
        if ($key >= $index)
        {
            $array1[] = $value;
            break;
        } else
        {
            $array0[] = $value;
        }
    }
    $array[0] = implode(' ', $array0);
    $array[1] = implode(' ', $array1);
}
$name = 'TV_Show_Name_785_www.website.com';
result: 
array (
  0 => 'TV Show Name',
  1 => '785',
)
$name = 'FName_LName_DataX_002_www.website.com';
result: 
array (
  0 => 'FName LName DataX',
  1 => '002',
)
$name = 'Roberto_Carlos_01_www.website.com';
result: 
array (
  0 => 'Roberto Carlos',
  1 => '01',
)

您可能需要在此处使用Regexp。试试这个:

<?php
$matches = array();
$name = 'Roberto_Carlos_01_www.website.com';
preg_match('/([^_]+)_([^_]+)_('d+)_(.+)/', $name, $matches);
print_r($matches); // array elements 1-4 contain the sub-matches
?>

编辑

抱歉,没有意识到输入是可变的。试试这个:

<?php
$array = array();
$matches = array();
$name = 'Roberto_Carlos_01_www.website.com';
preg_match('/([^'d]+)('d+).+/', $name, $matches);
$array[0] = trim(str_replace('_', ' ', $matches[1])); // info before number
$array[1] = $matches[2]; // the number
print_r($array);
?>

首先,最好的方法是使用phpexplode()函数将这些数据放入数组

这样使用:

<?
$data = explode("_" $name);
//Then get the data from the new array.
$array[0] = $data[0]." ".$data[1]." ".$data[2];
echo $array[0];
echo $data[3];
//Array index 3 would contain the number.
?>

这将获得包括数字在内的所有数据。希望这能有所帮助!