Jump to content

How limit html tags in PHP


love_bug

Recommended Posts

Hi,

I am a beginner in php..

well i am stuck in a situation.

I want to limit image tag <img> to 1 or 2 only.

 

suppose :

<?php
$string = "<img src=1> this is text <img src=2> <img src=3> here\'s some text <img src=4>";
echo limitImage($string);

function limitImage {
// Some function to do remove more than 1 img tags ..
}
?>

 

Output : <img src=1> this is text  here\'s some text

I hope you understood.. i think its simple.. but i have no idea how to do that..

 

thank you.

Link to comment
https://forums.phpfreaks.com/topic/72328-how-limit-html-tags-in-php/
Share on other sites

could use something like

 

 


<?php
function str_replace_every_other($needle, $replace, $haystack, &$count=null, $replace_first=true) {
    $count = 0;
    $offset = strpos($haystack, $needle);
    //If we don't replace the first, go ahead and skip it
    if (!$replace_first) {
        $offset += strlen($needle);
        $offset = strpos($haystack, $needle, $offset);
    }
    while ($offset !== false) {
        $haystack = substr_replace($haystack, $replace, $offset, strlen($needle));
        $count++;
        $offset += strlen($replace);
        $offset = strpos($haystack, $needle, $offset);
        if ($offset !== false) {
            $offset += strlen($needle);
            $offset = strpos($haystack, $needle, $offset);
        }
    }
    return $haystack;
}

//Use it like this:
$str = "one two one two one two";
echo str_replace_every_other('one', 'two', $str, $count).'<br />';
//two two one two two two
echo str_replace_every_other('one', 'two', $str, $count, false).'<br />';
//one two two two one two
?>


Thanks.. wish i could write the code..

the code seem to be working.. but it can not find image tags with different values..

can you show me how can i use it with perg_replace?

 

<?php
$URLSearchString = "a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";
$str  = preg_replace("(\<img src=([$URLSearchString]*)\](.+?)\</a>)", '$2', $str );
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.