简体   繁体   English

PHP正则表达式在字符之间或字符串结尾之间进行选择

[英]PHP Regular Expression select between characters or to end of string

I have been working on this problem for several days and it's starting to drive me crazy. 我已经在这个问题上工作了几天,它开始让我发疯。 I'm comfortable using regular expressions but this one thing seems to be escaping me. 我很喜欢使用正则表达式,但是这一件事似乎正在使我逃避现实。
I need to match a string between a set of characters if they exist otherwise it should match to the end of the line. 我需要在一组字符之间匹配一个字符串(如果存在的话),否则它应该与该行的末尾匹配。

For example: I'm just trying to get "content" out of the following example: 例如:我只是想从以下示例中获取“内容”:

$str1="title:content @description"
$str2="title:content"
preg_match("/:(.*?)[(@)|(:)|(\*)]?$/",$str1,$content);
preg_match("/:(.*?)[(@)|(:)|(\*)]?$/",$str2,$content);

$str1 outputs:"content @description" $ str1输出:“ content @description”

$str2 outputs:"content" $ str2输出:“内容”

note: the strings may be in a different order or may not have a special character (@,:,or *) in it or they might have one so there's no "end of string" character that will be common besides "end of line". 注意:字符串的顺序可能不同,也可能没有特殊字符(@ 、:或*),或者它们可能有一个特殊字符,因此除了“行尾”外没有其他“字符串结尾”字符会很常见”。

I've tried every combination i can think of to make the entire "or" statement conditional and read a ton of posts with similar but not quite the same question. 我已经尝试过我可以想到的每种组合,以使整个“或”陈述成为条件,并阅读大量类似但不完全相同的问题。

You can write: 你可以写:

preg_match("/:(.*?)(?:[@:*]|$)/", $str1, $content);

(note that the match ends at one of @:* or end-of-string, using | ; your version has the [@:*] optional, but makes the end-of-string mandatory.) (请注意,匹配使用|结束于@:* 字符串结尾之一),您的版本具有[@:*]可选,但使字符串结尾为必选。)

or simply: 或者简单地:

preg_match("/:([^@:*]*)/", $str1, $content);

(meaning "a colon, followed by zero or more characters that aren't in @:* "). (表示“冒号,后跟零个或多个@:*字符”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM