簡體   English   中英

正則表達式從結束PHP的兩個字符之間的字符串

[英]regex string between two characters from end php

我試圖讓字符串做正則表達式的一部分。 例如。

$input = "This is a 'wonderful' day except i am 'stuck' here"

我想這兩者之間的所有字符'秒。

為此,我正在使用

preg_match('~\'(.*?)\'~', $input, $output);

但是我得到的結果僅在$output[0] wonderful

我做錯了什么? 如何獲得第二部分,即stuck在此示例中?

編輯:我在檢查$ output [1]后問了這個問題。 stuck ”不存在!

除了從我的程序中對其進行測試之外,我還嘗試了一個在線正則表達式測試器。 結果如下:

http://s30.postimg.org/g6dj5xvmp/Selection_009.png

像這樣

<?php
$str = "This is a 'wonderful' day except i am 'stuck' here";
preg_match_all("/'(.*?)'/", $str, $matches);
print_r($matches[1]);

輸出:

Array
(
    [0] => wonderful
    [1] => stuck
)

這真的很簡單。 您使用preg_match ,它試圖找到一個給定的模式之一次數,找到所有比賽使用preg_match_all
兩者的工作方式相同: $matches數組將具有分配給索引0(包括引號) 的完整模式匹配 ,並且組將分配給所有后續索引(在這種情況下, $matches[0]將包含引號內的字符)。 區別在於preg_match_all將為上述索引分配數組 ,列出該模式的每個匹配項。

preg_match("/'([^]+)'/", $input, $matches);
var_dump($matches);

將給出這樣的數組:

array(
    "'wonderful'",    //because the pattern mentions the ' chars
    "wonderful"       //because I'm grouping the chars inside the '
);

而此代碼:

preg_match_all("/'([^']+)'/", $input, $matches));

給你:

array (
   //array of full matches, including the quotes
   array (
       '\'wonderful\'',
       '\'stuck\'',
   ),
   //array with groups
   array (
       'wonderful',
       'stuck',
   ),
);

如您在此實時示例中所見

我對表達式進行了一些簡化,因為您對用單引號“分隔”的內容感興趣,因此,我將每個非'匹配並分組,將每個非'都跟在單引號之后,然后依次跟上另一個單引號。 因此,您要匹配的char-class只是[^'] ... ...,除了'之外。
您可以對這種建議的模式進行可能的微優化,就是使用所有格量詞 ++ ,它類似於{1,} 或者,如果要在找到''匹配空字符串,則可以使用*+ 所以

if (preg_match_all("/'([^']++)'/", $subject, $matches))
    var_dump($matches);

應該做的把戲

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM