PHP str_replace标签

时间:2013-07-22 13:12:29

标签: php

我在PHP中有一个字符串,其中包含一些我想要更改的字符: 例如,这是一个字符串:

$string = '***ROOMS*** The rooms and bathrooms were fully renovated in 2006. They are reported to be quite small but are very clean, well maintained and with modern bathrooms. Rooms are tastefully designed with warm colours and pine wooden furniture. ***RESTAURANTS & BARS*** There is no restaurant in the hotel however there the comfortable ground floor lounge is open all day where ';

我想打印这样的段落:

<b>ROOMS</b><br>
 The rooms and bathrooms were fully renovated in 2006. They are reported to be quite small but are very clean, well maintained and with modern bathrooms. Rooms are tastefully designed with warm colours and pine wooden furniture.<br>
<b>RESTAURANTS & BARS</b><br> 
There is no restaurant in the hotel however there the comfortable ground floor lounge is open all day where 

这意味着******之间的字符串变为:<br><b> string </b><br>

是否存在使用str_replace或模式执行此操作的方法?

由于

4 个答案:

答案 0 :(得分:4)

试试这个:

$string = '***ROOMS*** The rooms and bathrooms were fully renovated in 2006. They are reported to be quite small but are very clean, well maintained and with modern bathrooms. Rooms are tastefully designed with warm colours and pine wooden furniture. ***RESTAURANTS & BARS*** There is no restaurant in the hotel however there the comfortable ground floor lounge is open all day where ';
echo preg_replace("/\*\*\*([A-Za-z\& ]*)\*\*\*/", '<br><b>$1</b><br>', $string);

更新:echo preg_replace("/\*{3}([^*]*)\*{3}/", '<br><b>$1</b><br>', $string);

答案 1 :(得分:3)

preg_replace("/\*{3}(.*)\*{3}/Usi", "<br><b>\\1</b><br>", $text);

答案 2 :(得分:2)

您需要使用正则表达式来完成此任务。

类似的东西:

$newString = preg_replace('/\*\*\*([^*]+)\*\*\*/','<br/><b>$1</b><br/>',$string);

这将捕获一对***之间的所有内容。

答案 3 :(得分:0)

function doReplace($string)
    {
        //You can add to the following array
        //for multiple items to find within
        //the string
        $find    = array('/\*\*\*(.*?)\*\*\*/',
                         '/\*(.*?)\*/');

        //Set the replacement for each item above.
        //Make sure all the replacements are in the
        //same order for the items your finding.
        $replace = array('<b>$1</b>',
                         '<i>$1</i>');

        //Finally, do the replacement.
        return preg_replace($find, $replace, $string);
    }

    $string = '***ROOMS*** The *rooms* and bathrooms were fully renovated in 2006. They are reported to be quite small but are very clean, well maintained and with modern bathrooms. Rooms are tastefully designed with warm colours and pine wooden furniture. ***RESTAURANTS & BARS*** There is no restaurant in the hotel however there the comfortable ground floor lounge is open all day where ';

    echo doReplace($string);

如果您决定进行多次替换,上述功能可以为您解决,只需添加它就可以做到这一点。