在php中使用preg_replace之前选择文本

在php中使用preg_replace之前选择文本,php,preg-replace,Php,Preg Replace,我需要从“文本”中提取“文本”。我尝试以下代码: echo preg_replace('/(.*)\#/', '', 'text#'); 但它不起作用。我的错误在哪里?您忘了包含对文本的引用-请参阅$1: 与使用正则表达式执行此任务不同,您可以或实际上应该只使用strpos和substr: 你得到了什么?什么不起作用?你只需要读一本基本的教程,你想做的很简单。你说的take是什么意思?去除你能写一个输入和期望输出的例子吗?e、 我想获得aaa或者其他什么 echo preg_replace('

我需要从“文本”中提取“文本”。我尝试以下代码:

echo preg_replace('/(.*)\#/', '', 'text#');

但它不起作用。我的错误在哪里?

您忘了包含对文本的引用-请参阅$1:


与使用正则表达式执行此任务不同,您可以或实际上应该只使用strpos和substr:


你得到了什么?什么不起作用?你只需要读一本基本的教程,你想做的很简单。你说的take是什么意思?去除你能写一个输入和期望输出的例子吗?e、 我想获得aaa或者其他什么
echo preg_replace('/(.*)\#/', '$1', 'text#');
echo substr_before('test#', '#')."\n"; // test# -> test
echo substr_before('foo#bar', '#'); // foo#bar -> foo

function substr_before($haystack, $needle) {
    // check if $haystack contains $needle, if so directly get the index of $needle
    if (($index = strpos($haystack, $needle)) !== false) {
        // chop off $needle and everything that trails it
        return substr($haystack, 0, $index);
    }
    return $haystack;
}