我从这样的数据库中获得了字符串:
$string1 = "1219.56.C38-.C382 Codex Azcatitlan";
$string2 = "1219.56.C45-.C452 Codex Cempoallan";
我如何将它们分为:
["1219.56.C38-.C382", "Codex Azcatitlan"]
["1219.56.C45-.C452", "Codex Cempoallan"]
请注意,如果我使用$ stringar1 = explode(“”,$ string1)等。 我会得到这个:
array(3)
(
[0] => string "1219.56.C38-.C382"
[1] => string "Codex"
[2] => string "Azcatitlan"
)
等
我需要“法典阿兹卡蒂特兰”
我事先不知道左右元素之间有多少个空格。 但是,我们可以假定它将始终大于1个空间。
答案 0 :(得分:4)
使用explode()的组合来限制第三个参数为array_map()的零件数,以删除多余的空格:
// this means you will have 2 items and all other spaces
// after first one will not be used for `explod`ing
$r = array_map('trim', explode(" ", $string1, 2));
答案 1 :(得分:3)
使用preg_split
并检查至少2个空格字符。
$string1 = "1219.56.C38-.C382 Codex Azcatitlan";
$string2 = "1219.56.C45-.C452 Codex Cempoallan";
print_r(preg_split('/\h{2,}/', $string1));
print_r(preg_split('/\h{2,}/', $string2));
如果$string
也应换行,请将\h
更改为\s
。 \h
是水平空白(制表符或空格),\s
是任何空白。
{}
在正则表达式中创建一个范围。内部的单个值是允许的字符数,内部的,
表示最小和最大范围。 2
是最小值,并且没有第二个值表示任意数量的其他匹配项。这与+
相同,但必须有两个,而不是一个匹配。
答案 2 :(得分:1)
您可以结合使用explode()
和substr()
$string1 = "1219.56.C38-.C382 Codex Azcatitlan";
// explode() on spaces
$explode = explode( ' ', trim( $string1 ) ); // apply trim() just in case there are ever leading spaces
$result = array(
$explode[ 0 ], // give me everything before the first space char
trim( substr( $string1, strlen( $explode[ 0 ] ) ) ) // give me everything starting from the first space char and apply trim()
);
var_dump( $result );
输出:
array(2) {
[0]=>
string(17) "1219.56.C38-.C382"
[1]=>
string(16) "Codex Azcatitlan"
}
答案 3 :(得分:1)
您可以结合使用const styles = theme => ({
root: {
flexGrow: 1,
width: "100%",
backgroundColor: theme.palette.background.paper
},
tabsIndicator: {
backgroundColor: "red",
textTransform: "capitalize"
},
tabRoot: {
"&:hover": {
color: "red",
opacity: 1,
textTransform: "capitalize"
},
"&$tabSelected": {
color: "red",
fontWeight: theme.typography.fontWeightMedium,
textTransform: "capitalize"
},
"&:focus": {
color: "red",
textTransform: "capitalize"
}
},
tabSelected: {}
});
,explode()
和array_shift()
implode()
输出:
$string1 = "1219.56.C38-.C382 Codex Azcatitlan";
// explode() on spaces
$explode = explode( ' ', trim( $string1 ) ); // apply trim() just in case there are ever leading spaces
$result = array(
array_shift( $explode ), // remove the first element from the array and give me it's value
trim( implode( ' ', $explode ) ) // $explode has it's first element removed so we can just implode it
);
var_dump( $result );
答案 4 :(得分:-2)
preg_match_all('~^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z0-9]+\s+([a-zA-Z0-9\s]+)~i', '1219.56.C38-.C382 Codex Azcatitlan', $matches);
print_r($matches);
Array ( [0] => Array ( [0] => 1219.56.C38-.C382 Codex Azcatitlan )
[1] => Array ( [0] => Codex Azcatitlan )
)