-2

編集:任意の文字列のユーザー入力を受け取ります。特定の構造を持つ文字列にのみフラグを付けたいです。

// 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 つのスラッシュを含むすべての文字列にフラグを立てます。これは正規表現で行うことができますか? ありがとう!

4

2 に答える 2

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] => 
        )

)
于 2013-04-18T15:24:22.613 に答える
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);
于 2013-04-18T15:13:49.420 に答える