regex - Wie komme ich zu den Übereinstimmungen, wenn ich preg_replace in PHP verwende?

original title: "regex - How can I get at the matches when using preg_replace in PHP?"


I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything.

preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str)

Ich versuche, die Großbuchstaben einiger Wörter zu erfassen und sie in span-Tags zu verpacken. Ich verwende preg_replace zum Extrahieren und Umschließen, aber es gibt nichts aus. preg_replace (...

Dies ist die Zusammenfassung nach der Übersetzung. Wenn Sie die vollständige Übersetzung anzeigen möchten, klicken Sie auf das Symbol "Übersetzen"

Alle Antworten
  • Translate

    You need to put the pattern in parentheses /([A-Z])/, like this:

    preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str)

  • Translate

    \0 will also match the entire matched expression without doing an explicit capture using parenthesis.

    preg_replace("/[A-Z]/", "<span class=\"initial\">\\0</span>", $str)

    As always, you can go to or<whatever search term> to search the documentation quickly. Quoth the documentation:

    \0 or $0 refers to the text matched by the whole pattern.

  • Translate

    From the preg_replace documentation on

    replacement may contain references of the form \n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern.

    See Flubba's example.

  • Translate

    Use parentheses around your desired capture.