【问题标题】:str_replace with a bunch of code phpstr_replace 用一堆代码 php
【发布时间】:2012-12-03 19:01:28
【问题描述】:

我有一些来自数据库的内容。而且我想用一堆代码替换内容的具体单词。

来自数据库的内容例如:

感谢您对我们网站的关注。
{FORMINSERT}
你可以 也可以拨打1234567890联系我们

我想用一堆 PHP 代码替换字符串 {FORMINSERT}。如果它是一个普通的文本字符串,我可以简单地使用 str_replace 替换它。

但是替换的内容不是简单的文本而是表单代码。

想替换这个{FORMINSERT}

举例:

<form method="post" id="form1" action="<?php echo KT_escapeAttribute(KT_getFullUri()); ?>">
    <table cellpadding="5" cellspacing="2" >
        <tr>
            <td width="84" ><a name="contact" id="contact"></a></td>
            <td width="384">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="2" ><h1>Contact Us</h1></td>
        </tr>
        <tr>
            <td ><label for="fullname">Name:</label></td>
            <td>
                <input type="text" name="fullname" id="fullname" value="<?php echo KT_escapeAttribute($row_rsscotts_contact['fullname']); ?>" size="47" />
                <?php echo $tNGs->displayFieldHint("fullname");?> <?php echo $tNGs->displayFieldError("scotts_contact", "fullname"); ?>
            </td>
        </tr>
        <tr>
            <td ><label for="phone">Phone:</label></td>
            <td>
                <input type="text" name="phone" id="phone" value="<?php echo KT_escapeAttribute($row_rsscotts_contact['phone']); ?>" size="47" />
                <?php echo $tNGs->displayFieldHint("phone");?> <?php echo $tNGs->displayFieldError("scotts_contact", "phone"); ?>
            </td>
        </tr>
        <tr>
            <td><label for="email">Email:</label></td>
            <td>
                <input type="text" name="email" id="email" value="<?php echo KT_escapeAttribute($row_rsscotts_contact['email']); ?>" size="47" />
                <?php //echo $tNGs->displayFieldHint("email");?> <?php echo $tNGs->displayFieldError("scotts_contact", "email"); ?>
            </td>
        </tr>
        <tr>
            <td><label for="tellus">Looking for:</label></td>
            <td>
                <textarea name="tellus" id="tellus" cols="37" rows="5"><?php echo KT_escapeAttribute($row_rsscotts_contact['tellus']); ?></textarea>
                <?php echo $tNGs->displayFieldHint("tellus");?> <?php echo $tNGs->displayFieldError("scotts_contact", "tellus"); ?>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" name="KT_Insert1" id="KT_Insert1" value="Submit" class="button-blue" /> 
                <input name="Reset" type="reset" value="Reset" class="button-grey" />
            </td>
        </tr>
    </table>
</form>

【问题讨论】:

  • 您在上面显示的&lt;form&gt; 一个简单的文本字符串。需要评估的不是 PHP 代码。
  • 他想用它替换一些 PHP 功能! @MichaelBerkowski
  • 您的&lt;form&gt; 是否实际上在&lt;?php ?&gt; 中包含任何PHP?如果是这样,请发布一个示例。否则,这可以通过str_replace() 来完成。
  • 是的,表单也有一些 php 代码。我已经更新了这个问题。很抱歉造成混乱。
  • OMG Dreamweaver + Interkt 扩展 :) 让我想起了糟糕的过去

标签: php string forms replace str-replace


【解决方案1】:

让我们假设来自您拥有的数据库的内容存储在变量 $db_content 中,您需要替换的 php 代码在 custom_code.phpso 中

if(strpos($db_content, "{FORMINSERT}") === true){
    //remove the tag
    str_replace("{FORMINSERT}", '',$db_content)
    //load the php code
   require_once("custom_code.php")
}
//if need, you can add more conditions using else-if & replace more tags. 

但最好转向MVC 模式,您可以通过模板轻松完成此类工作。这是我用于简单脚本的example

【讨论】:

  • 这不会将 custom_code.php 的内容放入 {FORMINSERT} 所在的位置,因此无法正常工作。我会在一秒钟内发布一条符合他要求的评论。
【解决方案2】:

如果您想将 HTML 和 PHP 代码组合在一起并将输出保存在一个变量中,可以使用 ob_start()

ob_start();
?>
    <form action="contact.php" method="post">
    Few fields here
    and submit button
    </form>
<?php

$forminsert = ob_get_clean();

然后你可以照常做你的str_replace()

但是,如果{FORMINSERT}可能出现也可能不出现,您可以使用preg_replace_callback()在不需要的情况下减少生成表单数据的成本:

$content = preg_replace_callback('/{(.*?)}/', function($match) {
    if ($match[1] == 'FORMINSERT') {
        // code to generate $forminsert
        return $forminsert;
    }
    return $match[0];
}, $content_from_db);

顺便说一句,这个函数也可以更通用地用于替换花括号之间的任何内容。

【讨论】:

    【解决方案3】:

    test1.php:

    $database_content = 'Thank you for interest on our web site.
    {FORMINSERT}
    You can also contact us by calling us to 1234567890';
    
    if(stripos($database_content, '{FORMINSERT}') !== FALSE){
        ob_start();
        include 'test2.php';
        $result = ob_get_clean();
    }
    
    $database_content = str_replace("{FORMINSERT}", $result, $database_content);
    
    echo $database_content;
    

    test2.php(您尝试插入的代码):

    echo 'hello world';
    

    结果:

    感谢您对我们网站的关注。你好世界 你也可以 致电1234567890联系我们

    所以就好像代码“echo 'hello world';”正坐在 {FORMINSERT} 所在的位置。您可以只创建一堆 PHP 文件来包含这样的内容,并制作一些 if 语句来处理替换。

    【讨论】:

      【解决方案4】:

      只要这样做,你的工作就解决了

             $forminser= " welcome to our website {FORMINSERT}";
             $form= "<form action='contact.php' method='post'>
                       Few fields here
                      and submit button
                    </form>" ;
             echo str_replace("{FORMINSERT}",$form,$forminser);
      

      编辑> 如果您希望表单中的 php 代码,那么这里是一个示例

           $var = "Few words here" ;
           $forminser= " welcome to our website {FORMINSERT}";
           $form= "<form action='contact.php' method='post'>";
           $form .= $var ;  // this php code here
           $form .= "  and submit button</form>" ;
               echo str_replace("{FORMINSERT}",$form,$forminser);
      

      编辑2

      zou 可以制作的全部代码来了。

          <?php
      
       $forminser= " welcome to our website {FORMINSERT}";
       $form = "<form method='post' id='form1' action=' " ;
       $form .=  KT_escapeAttribute(KT_getFullUri()); 
       $form .= " '><table cellpadding='5' cellspacing='2' >
               <tr>
               <td width='84' ><a name='contact' id='contact'></a></td>
               <td width='384'>&nbsp;</td>
               </tr>
               <tr>
               <td colspan='2' ><h1>Contact Us</h1></td>
               </tr>
                <tr>
                <td ><label for='fullname'>Name:</label></td>
                <td><input type='text' name='fullname' id='fullname' value=' " ;
      
      $form .= KT_escapeAttribute($row_rsscotts_contact['fullname']); 
      $form .= " ' size='47' /> ";
      $form .= $tNGs->displayFieldHint("fullname");
      $form .= $tNGs->displayFieldError("scotts_contact", "fullname"); 
      $form .= "</td>
               </tr>
               <tr>
               <td ><label for='phone'>Phone:</label></td>
               <td><input type='text' name='phone' id='phone' value= ' " ;
      $form .= KT_escapeAttribute($row_rsscotts_contact['phone']);
      $form .= " ' size='47' /> ";
      $form .= $tNGs->displayFieldHint("phone");
      $form .= $tNGs->displayFieldError("scotts_contact", "phone"); 
      $form .= '</td>
               </tr>
              <tr>
              <td><label for="email">Email:</label></td>
              <td><input type="text" name="email" id="email" value=" ' ;
      $form .= KT_escapeAttribute($row_rsscotts_contact['email']);
      $form .= '" size="47" />';
      $form .=  $tNGs->displayFieldError("scotts_contact", "email"); 
      $form .= '</td>
               </tr>
               <tr>
               <td><label for="tellus">Looking for:</label></td>
                <td><textarea name="tellus" id="tellus" cols="37" rows="5"> ';
      $form .=  KT_escapeAttribute($row_rsscotts_contact['tellus']); 
      $form .= '</textarea> ';
      $form .= $tNGs->displayFieldHint("tellus");
      $form .=  $tNGs->displayFieldError("scotts_contact", "tellus"); 
      $form .= '</td>
              </tr>
              <tr>
              <td></td>
               <td><input type="submit" name="KT_Insert1" id="KT_Insert1" value="Submit"  class="button-blue" /> <input name="Reset" type="reset" value="Reset" class="button-grey" /></td>
             </tr>
           </table>
          </form>
           ';
      
         echo str_replace("{FORMINSERT}",$form,$forminser);
       ?>         
      

      【讨论】:

      • 他已经说过它适用于像这样的常规字符串,他想用 PHP 代码替换它。
      • 是的,有些类似的东西。但它不会工作,因为它会破坏代码。我已经更新了有问题的示例。很抱歉造成混乱。
      • 如果不是这样,请使用 php 标签分享您的代码,我们将看到如何修复它
      • @goodmood:感谢您的努力。查看您的代码后。是的,它似乎很完美,它应该可以工作。谢谢!但是这段代码太保守了,增加了代码行。谢谢你的解决方案。我很感激。
      【解决方案5】:

      好的,这个怎么样。下面的代码允许您在内容中定义自定义 {words},它们将在解析时替换为其他内容。

      $contentFromDB = "Etiam porta sem malesuada magna mollis euismod. Donec ullamcorper nulla non metus auctor fringilla. {FORMINSERT}";
      
      echo matchTags($contentFromDB);
      
      
      function matchTags($content) {
         $pattern = '/{(\w+)}/i';
         $content = preg_replace_callback($pattern,"transformTags",$content);
         return $content;
      }
      
      
      function transformTags($word) {
      
          if ($word[1] == "FORMINSERT") {
      
              ob_start();
              ?>
              <form action="contact.php" method="post">
              Few fields here
                  and submit button
              </form>
              <?php 
              $content = ob_get_clean();
              return $content;
          }
      
          if ($word[1] == "somethingelse") {
      
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-02-09
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多