RegEx: how to change group contents

I have source code from a site that includes several image tags. I want to use the contents of the alt attribute as my src. Therefore I want to change this

<img src="http://www.example.com/img/img.png" alt="A Title">

:

<img src="http://www.example.org/img/a_title.png" alt="A Title">

To use the value of the alt attribute in the src attribute, I use the following regex

/(<img.+?src=").+?(".+?alt="(.+?)">)/

And use $1$3$2for subtitles.

I use PHP as a language.

But how can I change the third group (lowercase, replace spaces with underscores)?

+4
source share
2 answers

This is a working implementation using preg_match:

$input = "<img src=\"http://www.example.com/img/img.png\" alt=\"A Title\">";

$re = '~(<img\s*src=".*\/).*(\.[^"]*)("\s*alt="([^"]+).*)~';

preg_match($re, $input, $m);

$filtered_string = $m[1] . str_replace(" ","_",strtolower($m[4])) . $m[2] . $m[3];

Output:

<img src="http://www.example.com/img/a_title.png" alt="A Title">

Interactive implementation here .

UPDATE : preg_replace_callback:

$filtered_string = preg_replace_callback(
    '~(<img.*src=".*\/).*(\.[^"]*)(".*alt="([^"]+).*)~',
    function($m) {
      return $m[1] . str_replace(" ","_",strtolower($m[4])) . $m[2] . $m[3];
    },
    $str
);

- .

+1

PHP, preg_replace_callback:

$newLine = preg_replace_callback(
    '/(<img.+?src=").+?(".+?alt="(.+?)">)/',
    function($matches) {
        return $matches[1] . strtolower( str_replace(' ', '_', $matches[3]) ) . $matches[2];
    },
    $str
);
+1

Source: https://habr.com/ru/post/1612716/


All Articles