Reputation: 7260
I have these imaginary strings:
$txts=
array('<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>',
'<script>document.getElementById("demo").innerHTML = "Hello JavaScript!";</script>',
'document.getElementById("demo").innerHTML = "Hello JavaScript!";');
Now I would like an elegant simple solution to check if the <script>
and </script>
tags are surrounding the string and if not, surround the string with those tags.
So, $txts[0]
and $txts[1]
are valid but $txt[2]
should be surrounded with <script> </script>
I have a couple of solutions in my head but none 'sits' right with me, they are over complex or not clean.
Can you come up with a proper solution?
Upvotes: 1
Views: 99
Reputation: 164
/^<script[^<]*>/
makes sure the opening tag is complete
/<\/script>$/
makes sure the closing tag is there
I would do it this way:
$txts = array(
'<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>',
'<script>document.getElementById("demo").innerHTML = "Hello JavaScript!";</script>',
'document.getElementById("demo").innerHTML = "Hello JavaScript!";'
);
foreach ($txts as &$txt) {
if (!preg_match('/^<script[^<]*>/', $txt)) {
$txt = '<script>' . $txt;
}
if (!preg_match('/<\/script>$/', $txt)) {
$txt = $txt . '</script>';
}
}
var_dump($txts);
Output:
array(3) {
[0]=>
string(66) "<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>"
[1]=>
string(81) "<script>document.getElementById("demo").innerHTML = "Hello JavaScript!";</script>"
[2]=>
&string(81) "<script>document.getElementById("demo").innerHTML = "Hello JavaScript!";</script>"
}
Upvotes: 0
Reputation: 43169
Does it have to be a regex solution? Loops over the array and repairs it if necessary. Ensures that you have an array with open and closing tags in the end.
<?php
$txts=
array('<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>',
'<script>document.getElementById("demo").innerHTML = "Hello JavaScript!";</script>',
'document.getElementById("demo").innerHTML = "Hello JavaScript!";');
$opentag = "<script";
$closingtag = "</script>";
for ($i=0;$i<count($txts);$i++) {
if (strpos($txts[$i], $opentag) === false) $txts[$i] = $opentag.">".$txts[$i];
if (substr($txts[$i], -(strlen($closingtag))) !== $closingtag) $txts[$i] .= $closingtag;
}
print_r($txts); // all entries have open and closing tags in the end
?>
Upvotes: 1
Reputation: 9432
Check each array element:
foreach($txts as $txt) {
return is_int(strpos($txt, '<script')) && is_int(strpos($txt, '</script>')));
}
Or via a function:
function checkTags($beggining, $ending, $string)
{
return is_int(strpos($string, $beggining)) && is_int(strpos($string, $ending)))
}
Calling function for each element
foreach($txts as $txt) {
if(!checkTags('<script','</script>', $txt)) {
//treat error case
}
}
Note: is_int is used because the substring might be at possition 0 (the beginning as in your case) and evaluates as false.
Upvotes: 0