繁体   English   中英

替换PHP中的特殊字符串部分

[英]Replace special string part in PHP

我需要转换此字符串:

Hello, i'm **super** and **tall**.

对此:

Hello, i'm <big>super</big> and <big>tall</big>.

所以我用这个:

$string = "Hello, i'm **super** and **tall**.";
$old = array("**", "**");
$new = array("<big>", "</big>");
$newString = str_replace($old, $new, $string);

但这不起作用。

请你帮助我好吗 ?

谢谢。

您绝对可以清理一下,但这应该可以完成工作。

<?php
    $string = "Hello, i'm **super** and **tall**.";
    $pattern = '/\*{2}/';
    $replacement = '<big>';
    $result =  preg_replace($pattern, $replacement, $string);

    $pattern2 = '/\b(<big>)/';
    $replacement = '</big>';
    echo preg_replace($pattern2, $replacement, $result);
?>

我对数组使用正则表达式,但是第一个正则表达式/\\*{2}/寻找2 **。 如果找到2 **,它将替换为<big> 然后,第二个正则表达式\\b(<big>)将查找所有奇数次出现(或结束标记)并将其替换为适当的结束html标记。 希望这可以帮助!

您需要区分开始标记和开始标记,以便str_replace可以以您要求的准确度完成工作。 例:

<?php 
$string = "Hello, i'm *begin*super*end* and *begin*tall*end*.";
$old = array('*begin*', '*end*');
$new = array("<big>", "</big>");
$newString = str_replace($old, $new, $string);

echo $newString;
?> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM