Rumah  >  Soal Jawab  >  teks badan

Padankan perkataan tertentu selepas memadankan ayat lengkap menggunakan ungkapan biasa

Saya seorang pemula. Saya cuba mencari nama penuh dalam mana-mana baris di bawah dan tidak ada Obituary for

<h2>Obituary for John Doe</h2>
<h1>James Michael Lee</h1>

Ekspresi biasa saya adalah seperti ini.

(<h1>(.+?)<\/h1>|<h2>Obituary\sfor\s(.+?)<\/h2>)

Saya masih mendapat obituari John Doe. Bagaimana hendak memadamkan 讣告。如何删除 obituari ?

P粉872101673P粉872101673174 hari yang lalu397

membalas semua(2)saya akan balas

  • P粉775788723

    P粉7757887232024-04-02 10:10:01

    Bolehkah anda melakukan sesuatu seperti ini tanpa menggunakan ungkapan biasa?

    /**
     * @description : Function extracts names from html header tags
     * @example : "

    Obituary for John Doe

    James Michael Lee

    " -> ["John Doe", "James Michael Lee"] * @param $html string * @return []string : list of full names */ function extractFullNames($html) { $regex = '/(.*?)<\/h[1-2]>/'; preg_match_all($regex, $html, $matches); $names = $matches[1]; $names = array_map('trim', $names); $names = array_map('strip_tags', $names); $names = array_map('strtolower', $names); $names = array_map('ucwords', $names); $names = array_map('removeObituary', $names); return $names; } /** * @description : Function used to remove "Obituary For" if present * @example : "Obituary For John Doe" -> "John Doe" * @param $name string * @return string : name without "Obituary For" */ function removeObituary($name) { $name = str_replace("Obituary For ", "", $name); return $name; } // Test cases $html = '

    Obituary for John Doe

    James Michael Lee

    '; $names = extractFullNames($html); $expected = ['John Doe', 'James Michael Lee']; echo "Expected: " . implode(', ', $expected) . "\n"; echo "Actual: " . implode(', ', $names);

    balas
    0
  • P粉394812277

    P粉3948122772024-04-02 09:09:58

    Semua jalan menuju ke Rom, anda boleh melakukan ini:

    |2>Obituary\sfor\s)\K[^><]+

    Sila lihat demo ini di regex101. Perlawanan akan berlangsung dalam $out[0].

    K Tetapkan semula Bermula dengan laporan permainan. Lihat Soalan Lazim Ungkapan Biasa SO untuk maklumat lanjut.

    balas
    0
  • Batalbalas