在PHP中使用特殊字符剪切字符串

时间:2012-10-16 04:17:57

标签: php string

我正在搜索一个函数来剪切以下字符串并获取所有内容BEFORE和AFTER

I need this part<!-- more -->and also this part

结果应为

$result[0] = "I need this part"
$result[1] = "and also this part"

感谢任何帮助!

3 个答案:

答案 0 :(得分:8)

在PHP中使用explode()函数,如下所示:

$string = "I need this part<!-- more -->and the other part.
$result = explode('<!-- more -->`, $string) // 1st = needle -> 2nd = string

然后你打电话给你的结果:

echo $result[0]; // Echoes: I need that part
echo $result[1]; // Echoes: and the other part.

答案 1 :(得分:1)

您可以使用正则表达式轻松完成此操作。有人可能会因为用正则表达式解析HTML / XML而哭泣,但没有太多的背景,我会给你最好的东西:

$data = 'I need this part<!-- more -->and also this part';

$result = array();
preg_match('/^(.+?)<!--.+?-->(.+)$/', $data, $result);

echo $result[1]; // I need this part
echo $result[2]; // and also this part

如果要解析HTML,请考虑阅读parsing HTML in PHP

答案 2 :(得分:1)

使用preg_split。也许是这样的:

<?php
$result = preg_split("/<!--.+?-->/", "I need this part<!-- more -->and also this part");
print_r($result);
?>

输出:

Array
(
    [0] => I need this part
    [1] => and also this part
)