Zum Inhalt springen
View in the app

A better way to browse. Learn more.

Fachinformatiker.de

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

[PHP][Regex] Alle HTML-Anker in einem String zählen

Empfohlene Antworten

Veröffentlicht

Hallo!

Ich bin unerfahren auf dem Gebiet der regulären Ausdrücke, möchte aber gerne die Anzahl aller a-Tags in einem String unter Zuhilfenahme eines Regex zählen. So weit bin ich schon:


$code = '<a href="#">test</a> <a href="#">test</a>';
$anzahl = preg_match_all('/<a(.+)href="(.+)"(.*)>(.*)<\/a>/i', $code, $items);
[/PHP]

$anzahl ist allerdings 1 und $items sieht so aus:

[code] Array ( [0] => Array ( [0] => <a href="#">test</a> <a href="#">test</a> ) [1] => Array ( [0] => href="#">test</a> <a ) [2] => Array ( [0] => # ) [3] => Array ( [0] => ) [4] => Array ( [0] => test ) ) [/code]

Hat jemand einen Tipp?

Danke und Grüße, Tobias


$code = '<a href="#">test</a> <a href="#">test</a>';
$anzahl = preg_match_all('/<a(.+)href="(.+)"(.*)>(.*)<\/a>/i', $code, $items);
[/PHP]

Stichwort: [b]minimales[/b] Matching:

Folgender Regex sollte das leisten, was dir vorzuschweben scheint:

[PHP]
$code = '<a href="#">test</a> <a href="#">test</a>';
$anzahl = preg_match_all('/<a(.+?)href="(.+?)"(.*?)>(.*?)<\/a>/i', $code, $items);

Hint: Auf die "?" achten...

Super! Funkt! Danke! Was hat es denn mit diesen Fragezeichen auf sich?

Super! Funkt! Danke! Was hat es denn mit diesen Fragezeichen auf sich?
Das ist genau das "minimale" Matching.

Also normal ist ein Regex, wie bei dir (.+), sozusagen "gierig", und versucht, so viele Zeichen wie möglich darauf matchen zu lassen, also in die Klammern zu packen und als Ergebnis zurückzuliefern. In deinem ersten Versuch kam daher als erstes die gesamte Zeichenfolge ins Result (in welcher das tatsächlich gesuchte übrigens nochmal enthalten ist).

Mit dem ? hingegen wird der Regex "genügsam", und liefert als (.+?) zurück, sowie überhaupt was passt.

Archiv

Dieses Thema wurde archiviert und kann nicht mehr beantwortet werden.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.