2013-04-18 34 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] => 
     ) 

) 
相关问题