如何为我的包含简短博客的网站创建 Twitter 分享 link

How to create Twitter Share link for my website containing short blogs

我想从我的网站创建一个 Twitter 分享 link,通过从 PHP 数据库获取数据来分享用户博客的前几行。博客的数据在数据库中以HTML格式存储。我尝试获取数据并将其转换为 HTML 解码字符,但是当我尝试将转换后的字符用于 Twitter link 时,它会在发布推文之前重新添加 HTML chars/tags。附上图片供参考。

<script>
 
    function share(a) {
              let share_poem_ID = "#share-modal-" + a;
              document.querySelector(share_poem_ID).style.display = "block";
            }
    
    function shareClose(b) {
              let share_poem_ID = "#share-modal-" + b;
              document.querySelector(share_poem_ID).style.display = "none";
            }
</script>

<?php
    
    include 'connection.php';
    session_start();
    
    $query = " Select * From $dbtable";
    $result=@mysqli_query($connection,$query);
    $row=mysqli_fetch_assoc($result);
    
    foreach ($result as $row) {
     $Poem = $row['Poem'];
     $PoemShare =  htmlspecialchars_decode($Poem);
       echo "
        <div>
         <div class='the-poem'>
          <div class='poem'>$Poem</div>
         </div>
    
         <div class='poem-options'>
          <a class='share poem-option-list' id='report-btn-$ID' data-field-id='$ID' onclick='share($ID)'><i class='mdi mdi-share'></i></a>
         </div>
        </div>
    
      <!--- Share Modal --->
        <div class='modal-share' id='share-modal-$ID' role='dialog'>
         <div id='modal_content-share' class='modal-content-share'>
          <div class='page-container' id='page-content'>
            <span id='twitter$ID' class='share-option'>
              <i class='mdi mdi-twitter'></i>
                Share via Twitter
             </span>
           <script>
               $('#twitter$ID').on('click',function(){
                  window.open('https://twitter.com/intent/tweet?url=https://www.MartianJK.com/ms/login.php?u=$ID&text='$PoemShare'&hashtags=SpreadingSmiles', '_blank').focus();
                })
          </script>
         </div>      
        </div>
       </div>            
      ";
    
    }
    ?>

您可以使用 strip_tags():

$PoemShare =  strip_tags($Poem);

或保留 <br> 标签:

$PoemShare =  strip_tags($Poem, '<br>');
$PoemShare = strlen($Poem) > 99 ? substr($Poem,0,100).'...' : $Poem;    
$PoemShare = strip_tags($PoemShare, '<br>');
$PoemShare = preg_replace('<<br />>','%0A', $PoemShare);
$PoemShare = str_replace('&','%26', $PoemShare);
$PoemShare = str_replace('"','%22', $PoemShare);
$PoemShare = str_replace("'",'%27', $PoemShare);
echo var_dump($PoemShare); 

这段代码成就了我的作品。希望它也能帮助别人。归功于用户@Syscall