簡體   English   中英

使用正則表達式提取括號中的內容

[英]Extract whatever is in brackets using regular expressions

我真的根本不了解正則表達式,這很傷我的頭。

我有些文字看起來像這樣

blah blah blah (here is the bit I'd like to extract)

...而且我不太了解如何使用PHP的preg_split或等效命令來提取此內容。

我該怎么做呢? 在哪里可以了解預浸料的工作原理?

這樣的事情應該可以解決問題,以匹配()之間的內容:

$str = "blah blah blah (here is the bit I'd like to extract)";
if (preg_match('/\(([^\)]+)\)/', $str, $matches)) {
    var_dump($matches[1]);
}

你會得到:

string 'here is the bit I'd like to extract' (length=35)


基本上,我使用的模式搜索:

  • 開頭( ;但是as(具有特殊含義,必須轉義: \\(
  • 不是右括號的一個或多個字符: [^\\)]+
    • 這已被捕獲,因此我們以后可以使用它: ([^\\)]+)
    • 第一個(也是唯一一個,這里)捕獲的東西將以$matches[1]
  • 閉幕) ; 在這里,這也是一個必須轉義的特殊字符: \\)
<?php

$text = "blah blah blah (here is the bit I'd like to extract)";
$matches = array();
if(preg_match('!\(([^)]+)!', $text, $matches))
{
    echo "Text in brackets is: " . $matches[1] . "\n";
}

暫無
暫無

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

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