Jump to content
Stancobridge

How Can Select First Paragraph select in a Post

Recommended Posts

Hello,

I have a variable ($post) that contains posted content from database. Now I want to select the first paragraph and insert a code after it (Ads precisely ).

Here is my code

<?php
    include "../modules/gfuncs.php";
    $topicId=(int)$_GET['id'];
    #check if topic exists
   $q=$conn->query("SELECT * FROM topics WHERE id='$topicId'") or die( $conn->error );
    if(mysqli_num_rows($q)==0){
        header("location: $thisDomain/notfound");
        exit;
    }
    #check for post
   $c4p=$conn->query("SELECT * FROM posts WHERE topicid=$topicId") or die($conn->error);
    if(mysqli_num_rows($c4p)==0){
        $delpost=$conn->query("DELETE FROM topics WHERE id=$topicId") or die($conn->error);
        header("location:$thisDomain/notfound");
        exit;
    }
   
    #new comment
   $notify=""; $err="";
    if(isset($_POST['post']) and isLoggedIn()){
        $msg=$_POST['msg'];
        $fid=(int)$_POST['fid'];
        $thisdate=time();
        $error=array();
        #if user uploads attachment
       if($_FILES['attach']['size']>0){
            $thumb=$_FILES['attach'];
            $thumbtmp=$thumb['tmp_name'];
            $thumbname=$thumb['name'];
            $thumbsize=$thumb['size'];
            $targetDir="thumbs/$thumbname";
            $ext=pathinfo($targetDir, PATHINFO_EXTENSION);
            $allowed=array("jpg","gif","png");
            if(!in_array($ext, $allowed)){
                $error[]="Invalid thumbnail format";
            } elseif($thumbsize > 2097152){
                $error[]="Thumbnail size exceeded limit";
            }
        }
        if(!$msg or empty($msg)){
            $error[]="Please enter a comment";
        } elseif( strlen($msg)<3){
            $error[]="Comment too short";
        }
        if(count($error)==0){
            $newAttachName="";
            if($_FILES['attach']['size']>0){
                $newAttachName=encrypt(time()*rand(), 15).".jpg";
                @move_uploaded_file($thumbtmp, "thumbs/$newAttachName");
            }
            $save=$conn->query("INSERT INTO posts SET topicid=$topicId, forumid=$fid, poster='$curUser', postdate=$thisdate, post='$msg', attachment='$newAttachName'") or die($conn->error);
            $notify='<div class="successHolder">Comment Successfully Added!</div>';
        } else {
            $err=implode(",<br>", $error);
            $notify='<div class="errorHolder">'.$err.'</div>';
        }
    }
   
    $load=mysqli_fetch_object($q);
    $forumid=$load->forumid;
    $subject=_read($load->subject);
    $subjext=$load->subject;
    $poster=$load->poster;
    $views=$load->views;
    #update views
   $newviews=$views+1;
    $updviews=$conn->query("UPDATE topics SET views=$newviews WHERE id=$topicId") or die($conn->error);
    $postdate=$load->postdate;
    $postdate=date("d, M Y.", $postdate);
    $lastposter=$load->lastposter;
    $lastpostdate=$load->lastpostdate;
    $locked=$load->locked;
    $attachment=$load->attachment;
   
    #load forum info
   $fq=$conn->query("SELECT * FROM forums WHERE forumid=$forumid") or die($conn->error);
    $ft=mysqli_fetch_object($fq);
    $forumName=$ft->forumname;
    $forumUrl="$thisDomain/forum/$forumid/".urlize($forumName);
   
    #count posts
   $postCount=$conn->query("SELECT * FROM posts WHERE topicid=$topicId") or die( $conn->error);
    $totalPosts=mysqli_num_rows($postCount);
   
    #pagination
   $limit=13;
    $pagination= new paging;
    $pagination->totalResults($totalPosts);
    $pagination->rows_per_page($limit);
    $page=@$_GET['page'];
    $pagination->page($page);
    $pagination->thisPage("$thisDomain/forum/$forumid/topic/$topicId/".urlize($subjext));
    $paging=$pagination->paging();
    $paging.="<span class=\"tp\">Page ".$pagination->currentPage()." of ".$pagination->totalPages()."</span>";
    $anotif=""; $adminMenu="";
    if($isAdmin){
        if(isset($_POST['adminAct'])){
            $time=time();
            $act=$_POST['admin_act'];
            if($act=="tag_topic"){
                $qt=$conn->query("SELECT * FROM updates WHERE media='topic' AND media_id='$topicId'") or die($conn->error);
                if(mysqli_num_rows($qt)==0){
                    $qaa=$conn->query("INSERT INTO updates SET media='topic', media_id=$topicId, updatetime=$time") or die($conn->error);
                    $anotif='<div class="successHolder">Topic successfully tagged to homepage</div>';
                } else {
                    $anotif='<div class="errorHolder">Topic is already in updates</div>';
                }
            }
            elseif($act="untag_topic"){
                $qaa=$conn->query("DELETE FROM updates WHERE media='topic' AND media_id=$topicId") or die($conn->error);
                $anotif='<div class="successHolder">Topic successfully removed from updates</div>';
            }
            elseif($act=="del_topic"){
                $qaa=$conn->query("DELETE FROM topics WHERE id=$topicId") or die($conn->error);
                $delPost=$conn->query("DELETE FROM posts WHERE topicid=$topicId") or die($conn->error);
                $delFromUpdates=$conn->query("DELETE FROM updates WHERE media='topic' AND media_id=$topicId") or die($conn->error);
                header("location:$thisDomain/forum");
                exit;
            }
            elseif($act=="edit_topic"){
                header("location:$thisDomain/forum/topiceditor");
                exit;
            }
        }
        $adminMenu="<div class=\"ContentX\"><form method=\"post\" action=\"\">";
       #TAGGING: check if topic is tagged or not
      $qt=$conn->query("SELECT * FROM updates WHERE media='topic' AND media_id='$topicId'") or die($conn->error);
       if(mysqli_num_rows($qt)==0){
            $adminMenu.=" <input type=\"radio\" name=\"admin_act\" value=\"tag_topic\"> Tag Topic";
       } else {
            $adminMenu.=" <input type=\"radio\" name=\"admin_act\" value=\"untag_topic\"> Untag Topic";
       }
       $adminMenu.=" <input type=\"radio\" name=\"admin_act\" value=\"del_topic\"> Delete Topic";
       $adminMenu.=" <input type=\"radio\" name=\"admin_act\" value=\"edit_topic\"> Edit Topic <button type=\"submit\" name=\"adminAct\" class=\"w3-btn\">Submit</button></form></div>";
    }
   
    #resend query to initiate paging
   $postQ=$conn->query("SELECT * FROM posts WHERE topicid=$topicId ORDER BY id ASC LIMIT $pagination->offset,$pagination->rows_per_page") or die($conn->error);
   
    #load all posts
   $contents=""; $postMenu="";
    while($loadp=mysqli_fetch_object($postQ)){
        $postid=$loadp->id;
        $poster=$loadp->poster;
        $postdate=$loadp->postdate;
        $postAttach=$loadp->attachment;
        $post="";
        if($postAttach){
            $post='[img]'.$thisDomain.'/forum/thumbs/'.$postAttach.'[/img]';
        }
        $post.=$loadp->post;
        $post=_bbcode(_read($post));
        #get user info
       $usr=new userinfo;
        $usr->user($poster);
        $posterDP=$usr->get_info("dp");
        $posterCity=$usr->get_info("city");
        $posterState=$usr->get_info("state");
        $postdate=date("g:ia, jS M Y.", $postdate);
        if($isAdmin){
            $postMenu="\n<br>[<a href=\"$thisDomain/forum/editpost/$postid\">Edit Post</a>] / [<a href=\"$thisDomain/forum/delpost/$postid\">Delete Post</a>]";
        }
        $contents.=<<<eof
        <div class="aPost">
<table class="info">
                <tr>
                    <td width="75">
                        <img src="$thisDomain/user/dps/$posterDP" height="70" width="70" id="infoDP">
                    </td>
                    <td>
                    <a href="$thisDomain/profile/$poster"><span class="fa fa-user"></span> $poster</a>. $posterCity, $posterState<br>
                    <span class="fa fa-pencil"></span> $postdate
                </tr>
            </table>
 
<div class="msgBody">
 
 
 
$post
 
 
 
 
</div>$postMenu
        </div>
eof;
    }
   
    $pageTitle=$subject;
    include "../header.php";
   
?>

 

Share this post


Link to post
Share on other sites

Where's the relevant part of your code?

Share this post


Link to post
Share on other sites

One thing you can try, depending on how the paragraphs are stored, meaning if you have something like this for one $post:

<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>
<p>This is another paragraph. This is another paragraph. This is another paragraph from same post.</p>

You can use PHP substr function along with strpos to try and get the first paragraph like:

$firstPara = substr($post, 0, strpos(‘</p>’, $post));

This should retrieve the first paragraph. 

Share this post


Link to post
Share on other sites

Shouldn't it be $strpos($post, '</p>')?

I suggest you look for first '<p' string position, note: no closing tag '>' to avoid paragraphs with attributes being ignored.

Edited by dsonesuk

Share this post


Link to post
Share on other sites
6 hours ago, dsonesuk said:

Shouldn't it be $strpos($post, '</p>')?

Yes, good notice.  Edit: 

$firstPara = substr($post, 0, strpos($post, '</p>'));

 

Share this post


Link to post
Share on other sites
        $post = '<div>

<p class="classname">
            <span style="color: red">JJ</span> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
        <p>
            Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst.
        </p>
        <p>
            Fusce convallis, mauris imperdiet gravida bibendum, nisl turpis suscipit mauris, sed placerat ipsum urna sed risus. In convallis tellus a mauris. Curabitur non elit ut libero tristique sodales. Mauris a lacus. Donec mattis semper leo. In hac habitasse platea dictumst. Vivamus facilisis diam at odio. Mauris dictum, nisi eget consequat elementum, lacus ligula molestie metus, non feugiat orci magna ac sem. Donec turpis. Donec vitae metus. Morbi tristique neque eu mauris. Quisque gravida ipsum non sapien. Proin turpis lacus, scelerisque vitae, elementum at, lobortis ac, quam. Aliquam dictum eleifend risus. In hac habitasse platea dictumst. Etiam sit amet diam. Suspendisse odio. Suspendisse nunc. In semper bibendum libero.
        </p></div>';


        $firstPara = substr($post, strpos($post, '<p'), strpos($post, '</p>'));

        echo str_replace($firstPara, $firstPara . "<script> alert('hello')</script>", $post);

        ?>

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×