Question

I'm wanting to change the window location inside a dynamically generated div that has a onclick window location function, here is the div code;

<div class="buynow" id="item-1" onclick="window.location='store.php?id=1'">

I'm hoping to be able to use preg_replace to change the window location to something like;

<div class="buynow" id="item-1" onclick="window.location='item-one/'">

I've tried a few methods and failed miserably. Any tips on how I could achieve this?

Thanks.

Was it helpful?

Solution

$str = "<div class=\"buynow\" id=\"item-1\" onclick=\"window.location='store.php?id=1'\">";

echo preg_replace("/(<div.*?window\.location=)('.+')(.*?>)/", "\\1'item-one/'\\3", $str);

Working Example

Edit: added missing $.

OTHER TIPS

Try like so:

preg_replace('/(window\.location=\')[^"]+?(\'")/i', '\1item-one/\2', '<div class="buynow" id="item-1" onclick="window.location=\'store.php?id=1\'">');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top