我有一些这种风格的字符串:
$var = "a - it is a string"; // I want this output: 'it is a string'
$var = "m - it is second string"; // I want this output: 'it is second string'
所以这是我的模式:
[single character in the first of string]<space>-<space>{anything} // I want just {anything}
如何在 PHP REGEX 中做到这一点?
这是我的尝试(虽然不起作用,但我确信它真的离我想要的很远(
preg_replace("/^'w's+-'s+/","",$str);
编辑:
应该指出的是,我在现实中使用波斯字符。这里还有一个示例:
$var = 'ی - این یک متن تست است';
preg_replace('/^.'s-'s/', '', $var);
实时 PHP 演示
http://ideone.com/fvIKBE
正则表达式解释
^.'s-'s
Assert position at the beginning of a line «^»
Match any single character that is NOT a line break character «.»
Match a single character that is a “whitespace character” «'s»
Match the character “-” literally «-»
Match a single character that is a “whitespace character” «'s»
你可以使用这个:
$var = 'ی - این یک متن تست است';
echo preg_replace('/^'p{L}'h+-'h+/u', '', $var);
//=> این یک متن تست است
使用的正则表达式是:
^'p{L} # match unicode letter at start
'h+ # match 1 or more horizontal space
- # match 1 hyphen
'h+ # match 1 or more horizontal space
重要的是在此正则表达式中使用/u
修饰符来支持 unicode。
首先,您需要将/w
更改为 'w
。其次,为了匹配单个字符,您可以使用字符类(如果您只想匹配字母字符(,并且对于匹配字符串的其余部分,您可以使用修饰符.
后跟*
:
preg_replace("/^[a-z]'s+-'s+.*/","",$str);
另请注意,由于您使用锚^
来指定字符串的开头,因此如果要处理多行字符串,则需要对匹配全局使用标志m
和g
。
preg_replace("/^[a-z]'s+-'s+.*/m","",$str);
查看演示 https://regex101.com/r/gT9wB8/1
里德 更多关于正则表达式 https://www.regular-expressions.info
如果你正在处理 unicode 字符串,你可以使用标志u
,它使你的正则表达式引擎与 unicode 字符匹配。
另请注意,您需要更改字符范围或使用仅匹配一个字符(但所有字符(的点.
:
'/^.'s+-'s+.*/mu'
或:
'/^['u0622-'u06cc]'s+-'s+.*/mu'
演示 https://regex101.com/r/gT9wB8/2