Regex: How to find all occurrences of the string in the text but not those that are inside – Sergey Romanov Apr 11 '14 at 06:56

  • @SergeyRomanov, Try the DOM way suggested by hd1 instead and be patient ! **We are not here for that , we are here to help** – Shankar Damodaran Apr 11 '14 at 06:57
  • @ShankarDamodaran, that was not irritation or anger. I am sorry. This simply way I talk without intending to offend anyone. – Sergey Romanov Apr 11 '14 at 06:59
  • Quote myself: But I do not know what would be an HTML structure of the document. So I cannot use `$dom->getElementsByTagName('p')` because this placeholder may be in any part of the text I do not know where. In fact it is even more complex. I used [ID] as example to simplify but placeholder is like this `[PAID={"id":"1,2,3","other json data"}]Some text to hide[/PAID]`. And there may be HTML inside that pattern. And it may be inserted in to any input field or even insite template php file. – Sergey Romanov Apr 11 '14 at 07:08
  • 0

    How I did solve the problem. I have page HTML source in $body variable. So before run my search and replace.

    $pattern = '/\[ID\]/iU';
    $replace = array();
    if(preg_match_all('/(<textarea(.*)<\/textarea>)/isU', $body, $areas, PREG_SET_ORDER))
    {
        foreach($areas As $area)
        {
            if(preg_match_all($pattern, $area[0]))
            {
                $replace[] = array(
                    'src' => '{{TA_'.md5($area[0]).'}}',
                    'dst' => $area[0]
                );
                $body = str_replace($area[0], '{{TA_'.md5($area[0]).'}}', $body);
            }
        }
    }
    if(preg_match_all('/(<input([^>]*)>)/isU', $body, $inputs, PREG_SET_ORDER))
    {
        foreach($inputs As $input)
        {
            if(preg_match_all($pattern, $input[0]))
            {
                $replace[] = array(
                    'src' => '{{IP_'.md5($input[0]).'}}',
                    'dst' => $input[0]
                );
                $body = str_replace($input[0], '{{IP_'.md5($input[0]).'}}', $body);
            }
        }
    }
    

    Now when I finished all my replacements and parsing I do this.

    foreach($replace AS $rep)
    {
        $body = str_replace($rep['src'], $rep['dst'], $body);
    }
    
    Sergey Romanov
    • 2,580
    • 2
    • 21
    • 37