could you please tell me the way to get the first letter of two words that are linked with a specific character. For instance: hello_world I want to convert it to h_w
I tried to get the first letter of the two words. But I don’t know the way to keep the underscore between them
$str = 'hellow_world';
echo preg_replace("/(w)[^_]*?(?:_|$)/", "$1", $str);
2
Answers
Replace the following with nothing:
Try it on regex101.com.
Alternatively, you can match the whole word and replace it with the first letter using
$1
:Try it on regex101.com.
If you want to keep only the first character of a word not being an underscore, you can use
B
to assert a non word boundary not preceded by_
and match 1+ word chars other than_
Note that
w
can also match_
which you can exclude with a negated character class[^W_]
See a regex demo.
If the words must have at least one
_
where there is a word character before and after the underscore, you can make use of theG
anchor and 2 capture groups.The pattern matches:
(?:
Non capture group for the alternativesb([^W_])
A word boundary, capture a single word char other than_
in group 1[^W_]*
Match optional word chars other than_
|
OrG(?!^)
Assert the current postion at the end of the previous match, not at the start)
Close the non capture group(_[^W_])
Capture_
and a single word char other than_
in group 2[^W_]*
Match optional word chars other than_
See a regex demo and a PHP demo
Output