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
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
?>


Link to comment
Share on other sites

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 );
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.