2013-04-18 39 views
-2

編輯: 我將接收可以是任何字符串的用戶輸入。 我只想標記那些具有特定結構的字符串。preg_match使用特定字符串結構的正則表達式

// Flag 
$subject = 'Name 1 : text/Name 2 : text'; 

// Flag 
$subject = 'Name 1 : text/Name 2 : text/Name 3'; 

// Flag 
$subject = 'Name 3/Name 2/Name 3'; 

// Do NOT flag 
$subject = 'Name 1 : text, Name 2, text, Name 3'; 

// Do NOT flag 
$subject = 'This is another string'; 

因此,基本上標記每個至少有1個正斜槓的字符串。 這可以用正則表達式來完成嗎? 謝謝!

+0

您是否在尋找['explode(':',$ subject)'](http://www.php.net/explode)? – h2ooooooo

+0

我在尋找正則表達模式 – user558134

+2

你想要什麼輸出?規則是什麼?你有什麼嘗試? – h2ooooooo

回答

0

你需要清楚地定義你的same structure規則,但只是爲了讓你開始以下reges會爲您的兩個例子的工作:

$re='#^Name\s+\d+\s*:\s*\w+\s*/\s*Name\s+\d+\s*:\s*\w+(?:\s*/\s*Name\s+\d+)?$#i'; 
if (preg_match($re, $str, $match)) 
    print_r($match); 
1

我很可能會誤解又是什麼你想要的,但我認爲這可能是你想要的(無正則表達式):

<?php 
    $subject = 'Name 1 : text/Name 2 : text/Name 3'; 

    $subjectArray = array(); 
    $explode = explode('/', $subject); 
    for ($i = 0; $i < count($explode); $i++) { 
     list($name, $text) = explode(' : ', $explode[$i]); 
     $subjectArray[] = array(
      'name' => $name, 
      'text' => $text 
     ); 
    } 
    print_r($subjectArray); 
?> 

將輸出:

Array 
(
    [0] => Array 
     (
      [name] => Name 1 
      [text] => text 
     ) 

    [1] => Array 
     (
      [name] => Name 2 
      [text] => text 
     ) 

    [2] => Array 
     (
      [name] => Name 3 
      [text] => 
     ) 

) 
相關問題