在扩展 PCRE (php) 之后匹配 space 的正则表达式
Regex matching a space after extension PCRE (php)
我正在尝试迁移一个相当大且非常旧的数据库,其中一列包含文件名。问题是在这个字段中可以有多个文件名,由 space 分隔。
例如:
"Filename.mp3 file anem.mid fi le nam e.rm"
我试图用 preg_split()
拆分这些字符串,我能想出的最接近的正则表达式是
/(?<=\.[\w]{3})(\s)/
我知道 /(?<=\.[\w]+)(\s)/
行不通,因为在 PCRE 中,lookbehind 必须具有固定宽度。由于这是一个音乐数据库,因此也有非常规的扩展。
有什么建议吗?
您可以使用此正则表达式进行拆分:
~\.\w+\K\h+~
正则表达式详细信息:
\.
:匹配文字点
\w+
:匹配1+个单词字符
\K
: 重置匹配信息(忘记匹配数据)
\h+
: 匹配 1+ 个水平空格
如果您不想使用正则表达式,那么这是一个可行的解决方案:
<?php
$filename = "Filename.mp3 file anem.mid fi le nam e.rm";
// Temp storage for a single file's pieces
$new_filename = [];
// Store whole files
$filenames = [];
// Split up the string based on spaces
$spaces = explode( ' ', $filename );
// Loop the pieces broken by a space
foreach( $spaces as $piece )
{
// just keep adding pieces to this array
$new_filename[] = $piece;
// if this piece contains a period then we have a whole filename
if( strpos( $piece, '.' ) !== false )
{
// add this whole filename to the list by rejoining the temp var on spaces
$filenames[] = implode( ' ', $new_filename );
// reset the temp variable
$new_filename = [];
}
}
print_r( $filenames );
输出:
Array
(
[0] => Filename.mp3
[1] => file anem.mid
[2] => fi le nam e.rm
)
我正在尝试迁移一个相当大且非常旧的数据库,其中一列包含文件名。问题是在这个字段中可以有多个文件名,由 space 分隔。 例如:
"Filename.mp3 file anem.mid fi le nam e.rm"
我试图用 preg_split()
拆分这些字符串,我能想出的最接近的正则表达式是
/(?<=\.[\w]{3})(\s)/
我知道 /(?<=\.[\w]+)(\s)/
行不通,因为在 PCRE 中,lookbehind 必须具有固定宽度。由于这是一个音乐数据库,因此也有非常规的扩展。
有什么建议吗?
您可以使用此正则表达式进行拆分:
~\.\w+\K\h+~
正则表达式详细信息:
\.
:匹配文字点\w+
:匹配1+个单词字符\K
: 重置匹配信息(忘记匹配数据)\h+
: 匹配 1+ 个水平空格
如果您不想使用正则表达式,那么这是一个可行的解决方案:
<?php
$filename = "Filename.mp3 file anem.mid fi le nam e.rm";
// Temp storage for a single file's pieces
$new_filename = [];
// Store whole files
$filenames = [];
// Split up the string based on spaces
$spaces = explode( ' ', $filename );
// Loop the pieces broken by a space
foreach( $spaces as $piece )
{
// just keep adding pieces to this array
$new_filename[] = $piece;
// if this piece contains a period then we have a whole filename
if( strpos( $piece, '.' ) !== false )
{
// add this whole filename to the list by rejoining the temp var on spaces
$filenames[] = implode( ' ', $new_filename );
// reset the temp variable
$new_filename = [];
}
}
print_r( $filenames );
输出:
Array
(
[0] => Filename.mp3
[1] => file anem.mid
[2] => fi le nam e.rm
)