PHP将字符串拆分为整数,字符串和特殊字符

时间:2020-02-02 03:34:58

标签: php regex preg-split

我需要将这种格式的字符串const mongoose = require("mongoose"); const { Schema } = mongoose; const BlogSchema = Schema({ title: String, content: String, date: { type: Date, default: Date.now }, author: { type: Schema.Types.ObjectId, ref: "Blog" } }); module.exports = mongoose.model("Blog", BlogSchema); 分成如下数组,

blog.post("/", authenticateUsingJwt, (req, res) => { // Validating the req.body object const newPost = new Blog({ title: req.body.title, content: req.body.content, author: req.user_id }); newPost.save(); });

提供的字符串的数字和字符串可以是任意长度。我已经找到了php User.findOne({ username: "existingUserInDatabase" }) .populate("Blog") .then(user => res.send(user)) .catch(err => console.log(err)); 函数,但是不知道如何针对我的情况进行正则表达式。任何解决方案将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式来匹配各个部分:

^(\D+)(\d+):(.*)$

它匹配字符串的开头,一些非数字字符(\D+),后跟一些数字(\d+),冒号和{{1之后的一些字符}}和行尾之前。在PHP中,您可以使用:来查找所有匹配的组:

preg_match

输出:

$input = 'CF12:10';
preg_match('/^(\D+)(\d+):(.*)$/', $input, $matches);
array_shift($matches);
print_r($matches);

Demo on 3v4l.org

答案 1 :(得分:0)

如果有帮助,请尝试以下代码

 $str = 'C12:10';
 $arr = preg_match('~^(.*?)(\d+):(.*)~m', $str, $matches);
 array_shift($matches);                                                   
 echo '<pre>';print_r($matches);
相关问题