Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

shorttag matcher WordPress


i need to match a string however only when it is not inside a shorttag. suppose, i've the following texts in the post:

<blockquote>I have purchased a [shorttag]tablet[/shorttag] computers. this tablet is really awesome</blockquote>

here, i want to match the last tablet as it is not inside any short tag, like the first one. please also note that shorttag may have parameterss like:

[shorttag param1="xxx" param2="yyy"]tablet[/shorttag]

moreover, say, i will search using 'tablet' but it need to be able to find 'tablets' too (if possible).

thanks in advance.

Answers (1)


Ross Wilson answers:

Here is a quick regex snippit to do the matching, if you run it you can see that it will replace tablet with phone outside the shorttags, but not inside

$re = '~tablet(?!(.(?<!\[shorttag))*?\[/shorttag)~s';

$tx = '
[shorttag param1="xxx" param2="yyy"]this is a tablet[/shorttag]
this is a tablet for sale

echo htmlspecialchars(
preg_replace($re, 'phone', $tx));

Monster Coder comments:

thanks for your quick reply. seems it is working. however, here i re-wrote your expression as follows:

$pattern = "~tablet(?!(.(?<!\[[A-Za-z]))*?\[/[A-Za-z])~s";

as i wanted to match any shortcode pattern. seems it is working too. but i need to find dynamic keyword. here i searched for tablets. but i want to search dynamic.

$search = 'tablet computer';
$pattern = "~{$search}(?!(.(?<!\[[A-Za-z]))*?\[/[A-Za-z])~s";

may not work. i need to dynamically escape the values in the variable as it contains whitespace and other special chars. how can i dynamically escape them? any idea?


Ross Wilson comments:

You can just use preg_quote() on your search term like this
$search = preg_quote('tablet computer');
$pattern = "~{$search}(?!(.(?<!\[[A-Za-z]))*?\[/[A-Za-z])~s";

$tx = '
[shorttag param1="xxx" param2="yyy"]this is a tablet computer for sale[/shorttag]
this is a tablet computer for sale

echo htmlspecialchars(
preg_replace($pattern, 'phone', $tx));

Monster Coder comments:


i did same thing but i was not sure whether it will work or not.

will try again.