2012-02-18 44 views
0

我有一個變量,名爲$name,它包含了這樣的事情:獨立的數據,並把它們放入數組(PHP)

$name = 'FName_LName_DataX_Number_www.website.com';

我想把Number之前的所有數據在陣列withouth的下劃線和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'; 
+0

這很難分裂。首先,你不知道這個名字有多長,或者名稱有多少個詞,所以你排除了計數。接下來,如果我在看到一個數字時將我的「分裂」作爲基礎,那麼如果該名稱有一個數字呢?像第二個?第三個?它會切斷名稱。 – Joseph 2012-02-18 05:11:12

+0

我不這麼認爲,你說得對,我認爲唯一的辦法就是把這個名字的格式設置成這樣的名稱,名字叫Name_Number_www.website.com。在您的示例中爲 – Shixons 2012-02-18 05:18:40

+0

,您在一箇中有2個名字,在另一箇中有3個名字。你怎麼知道用戶只有「三言之意」? – Joseph 2012-02-18 05:20:52

回答

1

你的問題是特殊的使用正則表達式。但是在任何時候有人給出了這樣的解決方案,另一個人說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', 
) 
+0

._。這太完美了!謝謝! – Shixons 2012-02-18 05:23:34

+0

@ user177832 yuhuuu !!!純粹的樂趣... – 2012-02-18 05:26:25

-1

首先最好的辦法是使用PHP爆炸把這個數據到一個數組()函數

像這樣使用:

<? 

$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. 
?> 

這將得到所有的數據,包括數字。希望這可以幫助!

+0

謝謝,但我不能使用它,因爲我會打印總是相同的數組,並與此我不知道有多少數組有完整的名稱。 – Shixons 2012-02-18 05:16:24

+0

對不起,我不明白你的意思。你能解釋一下嗎? – spencer 2012-02-18 05:18:13

+0

我將使用'$ array [0]'來打印全名和'$ array [1]'來打印數字。 – Shixons 2012-02-18 05:20:04

0

您可能想在這裏使用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); 
?> 
+0

謝謝,但不能正確使用名稱中的更多元素。 – Shixons 2012-02-18 05:17:10

+0

它的作品,但像約瑟夫說,如果名稱有像第二個數字,它不工作。 – Shixons 2012-02-18 05:26:58

相關問題