簡體   English   中英

在php中使用preg_match查找給定字符串的子字符串?

[英]Using preg_match in php to find substring given string?

如何在PHP中使用preg_match來獲取以下字符串中的子字符串D30

$string = "random text sample=D30 more random text";

preg_match()將匹配組分配給第三個參數,並在匹配時返回1,在不匹配時返回0。 因此,檢查preg_match() == true是否為preg_match() == true ,如果是,則您的值將在$matches[0]

$string = "random text sample=D30 more random text";
if(preg_match('/(?<=sample=)\S+/', $string, $matches)) {
    $value = reset($matches);
    echo $value; // D30
}

正則表達式:

(?<=     (?# start lookbehind)
 sample= (?# match sample= literally)
)        (?# end lookbehind)
\S+      (?# match 1+ characters of non-whitespace)

演示


使用捕獲組而不是lookbehind:

$string = "random text sample=D30 more random text";
if(preg_match('/sample=(\S+)/', $string, $matches)) {
    $value = $matches[1];
    echo $value; // D30
}

正則表達式:

sample= (?# match sample= literally)
(       (?# start capture group)
 \S+    (?# match 1+ characters of non-whitespace)
)       (?# end capture group)

演示

暫無
暫無

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

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