开发者

How can I replace a string?

I have a string (this string comes from the database i.e. a dynamic string) that contains two <a> tags. E.g.:

$str = '<a href="http://www.google.com" key1="value1">Any string</a>
       <a key1="value1" href="http://www.google.com">Any string</a>';

How can I add a separate onclick attribute to the <a> tags in that string, i.e first <a> tag onclick="test1()", the next <a> tag onclick="test2()" etc., by using PHP preg开发者_StackOverflow_replace or another method?


$str = str_replace(' href="',' onclick="test(this)" href="',$str);

That's significantly faster than preg_replace since it doesn't have to match a pattern. This of course, depends on the way you're using it.


I didn't use this library, but with the help of PHP Simple HTML DOM Parser, you could use this code to try and add the functions:

//array containing your functions names
$functions = array(test1, test2);

//Parse the string to get the HTML DOM
$html = str_get_html($str);

//Retrieve the array of anchors
$links = $html->find('a');

//Loop through the anchors and add the onclick events
for($i=0;$i<count($links);$i++){
    $links[$i]->onclick = $functions[$i];
}

//return the html to the string
$html->save();

You'll probably have to test it a bit and change it so it could pass into your process.

EDIT: To adapt this solution so as to use unobtrusive JavaScript, you could replace $links[$i]->onclick by $links[$i]->id, and then add an eventHandler with javascript:

//Add an event listener that will trigger when the content of the page is loaded
document.addEventListener("DOMContentLoaded", function() {
    var i;

    //retrieve all the anchors
    var link = document.getElementsByTagName("a");
    //Loop through the anchors
    for(i=0; i<links.length; i++){
        //If the anchor has an id
        if(links[i].id){
            //retrieve the function
            var myFuncName = links[i].id;
            var myFunction = window[myFuncName];
            //add the event listener
            links[i].addEventListener("change", myFunction, false);
        }
    }
}, false);

It is important to retrieve the function as it is has been done here, as links[i].id is a string, and addEeventListener wouldn't have worked with a string instead of the function. As window.function is the same as window['function'], this do the conversion perfectly.

As with the PHP code, this could be object to change depending on your environment. For example if all the anchors who needs an onchange eventHandler are situated under a div tag with id "mylinks", you can change document.getElementsByTagName("a"); by document.getElementById("mylinks).getElementsByTagName("a");.


NOTE : This solution will only work with your current string pattern (which seems to be a collection of links)

NOTE 2 : You could also use unobtrusive javascript for this

To finally answer your question

$str =  str_ireplace ('<a ', '<a onclick="doSomething(this)"', $str);

http://php.net/manual/en/function.str-ireplace.php

EDIT

@Eldros pointed out that the methods need to be different for each link.

In that I would definitely suggest you take care of it on the client side. But if you must do this with PHP, you could use a library like Simple HTML DOM for DOM parsing. Note that this does not use DOM manipulation but rather string parsing. This may or may not matter to you.

This is an example from the documentation showing how to modify your string. See the documentation for full usage : http://simplehtmldom.sourceforge.net/manual.htm

// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

In your case, you'd just load your string with str_get_html and loop through it modifying your link one by one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜