preg_match

References

Syntax:

preg_match(
  string $pattern,
  string $subject,
  array &$matches = null,
  int $flags = 0,
  int $offset = 0
): int|false

Extract Values

Given an image tag string, e.g.: <img src="value" class="value" alt="value" />, return a standard class containing the attribute values.

  public function extractImageTagAttributes(string $imageTag) : \stdClass {
    $attrs = new \stdClass();
    foreach (['src', 'alt', 'class', 'style', 'title'] as $attr) {
      $pattern = '/' . $attr . '="(.*?)"/';
      $hasMatch = preg_match($pattern, $imageTag, $attrMatches);
      $attrs->{$attr} = ($hasMatch) ? $attrMatches[1] : '';
    }
    return $attrs;
  }

A person could write a knarly regex expression to do this in a single go, or use preg_match_all to match name="value" pairs. This provides a nice way of assigning empty strings to attributes that don’t exist in the tag.