Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7418189
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T07:50:27+00:00 2026-05-29T07:50:27+00:00

Regular Expression problem I have Regular Expression code handling graphic files. $view[content] = preg_replace(/(\<img

  • 0

Regular Expression problem

I have Regular Expression code handling graphic files.

$view[content] = preg_replace("/(\<img )([^\>]*)(\>)/i", "\\1 name='target_resize_image[]' onclick='image_window(this)' style='cursor:pointer;' \\2 \\3", $view[content]);

At web pages, if there is not ‘style” on html code, this code works fine. But if there is “style”, the “style” code was changed into “style=’cursor:pointer;”.

I wnat, if there is “style=’…'” at img, the style=’…'” is added. If not, the “style” code should be “style=’cursor:pointer;'”.

The “preg_replace” gets rid of “style=’aaaaaa'” at img code. That should be “style=’cursor:pointer'”.

code input

<img style="border-bottom: medium none; border-left: medium none; width: 160px; float: left; height: 160px; border-top: medium none; margin-right: 1em; border-right: medium none" alt="120131_12e1c8be2d6954ec9a3579ae57a64bfe_3EsTQWri2Zx9.gif" src="/data/cheditor4/1201/120131_02133169e006e1d08fc72fa5ff1e7a25_5KKOd8zrZhluXoqpiN.gif" /> 

code output

<img style="cursor:pointer" alt="120131_12e1c8be2d6954ec9a3579ae57a64bfe_3EsTQWri2Zx9.gif" src="/data/cheditor4/1201/120131_02133169e006e1d08fc72fa5ff1e7a25_5KKOd8zrZhluXoqpiN.gif" /> 

code – should be

<img style="cursor:pointer;border-bottom: medium none; border-left: medium none; width: 160px; float: left; height: 160px; border-top: medium none; margin-right: 1em; border-right: medium none" alt="120131_12e1c8be2d6954ec9a3579ae57a64bfe_3EsTQWri2Zx9.gif" src="/data/cheditor4/1201/120131_02133169e006e1d08fc72fa5ff1e7a25_5KKOd8zrZhluXoqpiN.gif" /> 

Any helpful comment would be appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T07:50:29+00:00Added an answer on May 29, 2026 at 7:50 am

    Your regexp creates this output:

    <img name='target_resize_image[]' onclick='image_window(this)' style='cursor:pointer;' style="border-bottom: medium none; border-left: medium none; width: 160px; float: left; height: 160px; border-top: medium none; margin-right: 1em; border-right: medium none" alt="120131_12e1c8be2d6954ec9a3579ae57a64bfe_3EsTQWri2Zx9.gif" src="/data/cheditor4/1201/120131_02133169e006e1d08fc72fa5ff1e7a25_5KKOd8zrZhluXoqpiN.gif" / >
    

    Please note, that you have -of course- two style attributes in this string. Apparently you use some kind of HTML validation, which automatically “fixes” this by removing the 2nd one and just leaves you with style='cursor:pointer;'.

    You could improve your regexp. Using a pattern like /(alt|style|src)=("[^"]*")/i with preg_match_all will allow you to extract the attributes of your img tag, then manipulate them and build a new HTML string from it.

    Anyway, I do not recommend manipulating HTML using RegExp’s at all. It is much more simple and robust to Use DOM tools. Have a look at the Simple HTML DOM Parser. This simple code

    require 'simple_html_dom.php'; // http://simplehtmldom.sourceforge.net/
    $html = str_get_html($img); // load HTML as DOM object
    $img = $html->find('img', 0); // find your tag
    $img->style = "cursor:pointer;".$img->style; // manipulate the style attr
    $img->name="target_resize_image[]"; // set other attr's
    $img->onclick="image_window(this)";
    echo htmlspecialchars($html); // output HTML as string
    

    gives you the output

    <img style="cursor:pointer;border-bottom: medium none; border-left: medium none; width: 160px; float: left; height: 160px; border-top: medium none; margin-right: 1em; border-right: medium none" alt="120131_12e1c8be2d6954ec9a3579ae57a64bfe_3EsTQWri2Zx9.gif" src="/data/cheditor4/1201/120131_02133169e006e1d08fc72fa5ff1e7a25_5KKOd8zrZhluXoqpiN.gif" name="target_resize_image[]" onclick="image_window(this)" />
    

    Voila! And it doesn’t depend on the order of your attributes, on used quotes, spaces and line-breaks.

    EDIT: WindStory has requested a non-DOM Solution

    The solution depends very much on the given strcuture of your input string. If you, for example, know for sure, that every given img already has a style attribute, you can do it with a plain replace:

    $img = str_replace('style="', 'style="cursor:pointer; ', $img); // add info to the given style-attr
    $img = str_replace('<img', '<img new_attribute="value" ', $img); // add new attrs
    

    Having less guarantees on your given tag, you can use the RegExp I mentioned above to extract the attributes from the img tag

    // extract attr's, depends on double quotes
    $Attrs = array();
    if (preg_match_all('/(alt|style|src)="([^"]*)"/i', $img, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
            $Attrs[$match[1]] = $match[2];
        }
    }
    
    // change/add attr's
    $Attrs['style'] = empty($Attrs['style']) ? 'cursor:pointer' : 'cursor:pointer; '.$Attrs['style'];
    $Attrs['name'] = 'target_resize_image[]';
    $Attrs['onclick'] = 'image_window(this)';
    
    // build new HTML
    $new_img = '<img ';
    foreach ($Attrs as $key => $value) $new_img .= $key.'="'.$value.'" ';
    $new_img .= '/>';
    

    See it in action here.

    Hope that helps.

    EDIT 2: WindStory has asked for a more fault-tolerant RegExp solution

    Here is a small function, to add/change attributes in a given HTML string. It supports single or double quotes for attribtues, but no missing quotes and it will not work, if a single quote is enclosed by double quotes and vice versa.

    function add_attr($html, $name, $value, $append = null) {
        $attr_pattern = "/\b({$name}=['\"])([^'\"]*)(['\"])/i";
        if (preg_match($attr_pattern, $html, $regs)) {
            if (!is_null($append)) {
                $value = $regs[2].$append.$value;
            }
            $replace = "\\1$value\\3";
            $html = preg_replace($attr_pattern, $replace, $html);
        } else {
            $tag_pattern = '/<[\w]+\b/i';
            $replace = "\\0 $name=\"$value\"";
            $html = preg_replace($tag_pattern, $replace, $html);
        }
        return $html;
    }
    

    Insert a html-Tag as $html, define the $name of the attribute and define the $value. If the attribute is already present, the value will be replaced, otherwise it will be added. If you set $append, the $value will be appended and $append will be used as concatenation sign.

    This

    $img = add_attr($img, 'style', 'cursor:pointer', '; ');
    $img = add_attr($img, 'name', 'target_resize_image[]');
    $img = add_attr($img, 'onclick', 'image_window(this)');
    echo htmlspecialchars($img);
    

    will outout

    <img onclick="image_window(this)" name="target_resize_image[]" style="border-bottom: medium none; border-left: medium none; width: 160px; float: left; height: 160px; border-top: medium none; margin-right: 1em; border-right: medium none; cursor:pointer;" alt="120131_12e1c8be2d6954ec9a3579ae57a64bfe_3EsTQWri2Zx9.gif" src="/data/cheditor4/1201/120131_02133169e006e1d08fc72fa5ff1e7a25_5KKOd8zrZhluXoqpiN.gif" />
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have one interesting problem. I must parse mail body (regular expression), get some
I have a little problem with my regular expression, that I use in PHP.
I have an odd problem with a regular expression in Java. I tested my
I have a problem with regular expressions! How can i count html tags with
I need a regular expression to solve the following problem (links to similar problems
I am having a problem with my regular expression: <a.*href=[\'](.*?)[\'].*>(.*?)</a> . It is, as
Here's the problem: split=re.compile('\\W*') This regular expression works fine when dealing with regular words,
What follows is a regular expression I have written to match multi-line pre-processor macros
I have the following regular expression /[^a-zA-Z0-9 ]/g I want include " in the
I have the following code in about 300 HTML files, I need to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.