使用 Preg_Replace 保留删除的值

发布于 2024-12-12 02:19:23 字数 169 浏览 0 评论 0原文

我正在使用 preg_replace 从字符串中删除一些内容。我想知道是否有一种方法可以将删除的内容保留在不同的变量中。这是我正在使用的:

$city = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $content[2]);

I am using preg_replace to remove some content from a string. What I am wondering is if there is a way to keep the stuff that is removed in a different variable. Here is what I am using:

$city = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $content[2]);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

娇纵 2024-12-19 02:19:23

首先使用 preg_match_all() 获取字符串中的所有匹配项,然后运行 ​​preg_replace() 进行实际替换。

First get all the matches in your string with preg_match_all() and then run preg_replace() to do the actual replacing.

我的痛♀有谁懂 2024-12-19 02:19:23

首先运行 preg_match() 来获取要替换的内容,然后按照您的操作替换内容。

Run a preg_match() first to get the content which will be replaced, and then replace the content as you do.

懵少女 2024-12-19 02:19:23

您可以使用 preg_replace_callback并在回调中替换它们之前将匹配项分配给变量:

$pattern = '/^([0-9]* \w+ )?(.*)$/';
$matches = array();
$replace = function($groups) use (&$matches)
{
    $matches = $groups;
    return $groups[2];
};
$city = preg_replace_callback($pattern, $replace, $content[2]);

var_dump($city, $matches);

但是,在您的具体情况下,您甚至根本不需要运行 preg_replace,您只需使用 preg_match >:

$pattern = '/^([0-9]* \w+ )?(.*)$/';
$subject= $content[2];
$r = preg_match($pattern, $subject, $matches);    
list($replaced,,$city) = $matches; # the result you're looking for.

You can use preg_replace_callback and assign the matches to variables before you replace them in your callback:

$pattern = '/^([0-9]* \w+ )?(.*)$/';
$matches = array();
$replace = function($groups) use (&$matches)
{
    $matches = $groups;
    return $groups[2];
};
$city = preg_replace_callback($pattern, $replace, $content[2]);

var_dump($city, $matches);

However in your specific case, you don't even need to run preg_replace at all, you can just use preg_match:

$pattern = '/^([0-9]* \w+ )?(.*)$/';
$subject= $content[2];
$r = preg_match($pattern, $subject, $matches);    
list($replaced,,$city) = $matches; # the result you're looking for.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文