gpt4 book ai didi

php - 在 strpos() 的字符串中使用正则表达式

转载 作者:IT王子 更新时间:2023-10-29 00:11:54 25 4
gpt4 key购买 nike

我想让脚本搜索 $open_email_msg ,不同的电子邮件会有不同的信息,但格式相同,如下所示。

我并没有真正使用正则表达式,但我想做的是每当我用它来搜索字符串时它会搜索“标题:[标题数据]”,“类别:[类别数据]。我问是因为我不认为是这样的

strpos($open_email_msg, "Title: (*^)"); 

甚至可以工作。

这只是整个代码的一小段,其余代码将信息插入 MySQL 表,然后发布到网站上的新闻文章中。

有人可以帮我找到解决办法吗?

严格的电子邮件格式:

News Update
Title: Article Title
Tags: tag1 tag2
Categories: Article Category, 2nd Article Category
Snippet: Article snippet.
Message: Article Message. Images. More text, more text. Lorem impsum dolor sit amet.

<?php
//These functions searches the open e-mail for the the prefix defining strings.
//Need a function to search after the space after the strings because the subject, categories, snippet, tags and message are constant-changing.
$subject = strpos($open_email_msg, "Title:"); //Searches the open e-mail for the string "Title"
$subject = str_replace("Title: ", "" ,$subject);
$categories = strpos($open_email_msg, "Categories:"); //Searches the open e-mail for the string "Categories"
$snippet = strpos($open_email_msg,"Snippet"); //Searches the open e-mail for the string "Snippet"
$content = strpos($open_email_msg, "Message"); //Searches the open-email for the string "Message"
$tags = str_replace(' ',',',$subject); //DDIE
$uri = str_replace(' ','-',$subject); //DDIE
$when = strtotime("now"); //date article was posted
?>

最佳答案

尝试为 preg_match 使用 PREG_OFFSET_CAPTURE 标志.像这样的:

preg_match('/Title: .*/', $open_email_msg, $matches, PREG_OFFSET_CAPTURE);
echo $matches[0][1];

这应该会为您提供字符串的初始位置。

请注意,我使用的正则表达式可能是错误的,并且没有考虑行结尾和其他内容,但这是另一个主题。 :)

编辑。你想要的更好的解决方案(如果我理解正确的话)是这样的:

$title = preg_match('/Title: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';

然后您会将标题放入 $title 变量中,如果没有找到标题,则为空字符串。

关于php - 在 strpos() 的字符串中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com