-1

I'm newbie to stackoverflow

So i have html file that has lots of <span style="display:none;">some text</span>

Their amount exceeds like 100 or 200 . I want to replace the inner text of the span with random strings

But i got 2 problems , the first one is that i cant find the right regex pattern to find span with inline style="display:none"

But i'm able to get all spans text with /<span (.*?)>(.*?)<\/span>/ . And here comes the second problem . I'm using php and here's my code

    preg_match_all('/<span (.*?)>(.*?)<\/span>/', $file, $matches);
    foreach ($matches as $value) {
        $string = str_replace($value, RandomString(), $file);
    } 

so it changes the inner texts of ALL spans but at once , RandomString() is a function that generates random string , and after str_replace it returns the changed the string , but all span's value are the same , as i get my random string generator only works once and the str_replace() replaces all found matches

I thought about recursion

function rec($string)
    {
        preg_match('/<span (.*?)>(.*?)<\/span>/', $string, $matches);
        if (!$matches) {
            return $string;
        }
        foreach ($matches as $value) {
            $string = str_replace($value,RandomString(), $string);
            rec($string);
        }
    }

But it returns 500 error...

So how can i replace the found matches step by step?

Example

<span>not to change text</span> 
<span style="display:none">change text</span>
<span style="display:none">change text</span>

I want it to be like

<span>not to change text</span> 
<span style="display:none">some random string</span>
<span style="display:none">other ddifferent random string</span>

Regex is mandatory

1 Answers1

0

It is better to use something like DOM

But you wrote regex is mandatory, so here is working sample:

preg_match_all('/<span .*?display:none.*?>(.*?)<\/span>/', $string, $matches);
foreach($matches[1] as $match) {
    $string = preg_replace('/>' . $match . '</', '>' . rand() . '<', $string, 1);
}
Konstantin Bogomolov
  • 1,278
  • 1
  • 11
  • 16