duanph1978 2016-06-02 06:24
浏览 46
已采纳

PHP如何从文本区域[关闭]读取[您的名字]

Check this:

Dear [NAME],
<br /><br />
Someone (hopefully you) requested a password reset at [SITE_URL].
<br /><br />
To reset your password, please follow the following link: [EMAIL_LINK]

in above lines there are names of the fields in [ ] in a text area of my php user management for email template. Please tell me how PHP read i.e [NAME] this....? is there a function.. if yes what is it and how...? i hope you all can understand what i wanna know...

Thanks

Best Regards

  • 写回答

3条回答 默认 最新

  • dsfhe34889789708 2016-06-02 06:40
    关注

    You can use preg_match_all to match all the keywords wrapped by square brackets:

    $text = 'Dear [NAME],
    <br /><br />
    Someone (hopefully you) requested a password reset at [SITE_URL].
    <br /><br />
    To reset your password, please follow the following link: [EMAIL_LINK]';
    
    preg_match_all('/\[([A-Z_]+)\]/', $text, $matches);
    

    By var_dumping the $matches variable you will get:

    array(2) {
      [0]=>
      array(3) {
        [0]=>
        string(6) "[NAME]"
        [1]=>
        string(10) "[SITE_URL]"
        [2]=>
        string(12) "[EMAIL_LINK]"
      }
      [1]=>
      array(3) {
        [0]=>
        string(4) "NAME"
        [1]=>
        string(8) "SITE_URL"
        [2]=>
        string(10) "EMAIL_LINK"
      }
    }
    

    So, let's suppose you will have an array of keywords to be replaced:

    $keywords = array(
        'NAME' => 'Mihai MATEI',
        'SITE_URL' => 'http://example.com/',
        'EMAIL_LINK' => '<a href="mailto:contact@example.com">contact@example.com</a>',
    );
    

    You can replace the keywords in the template as:

    foreach ($matches[1] as $key => $keyword) {
        $text = str_replace($matches[0][$key], $keywords[$keyword], $text);
    }
    

    Now if you var_dump the $text variable will get:

    Dear Mihai MATEI,
    <br /><br />
    Someone (hopefully you) requested a password reset at http://example.com/.
    <br /><br />
    To reset your password, please follow the following link: <a href="mailto:contact@example.com">contact@example.com</a>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大