从仅包含单词的字符串创建首字母缩略词
我正在寻找一种方法,可以从输入字段中提取每个单词的第一个字母并将其放入变量中。
示例:如果输入字段为“Stack-Overflow Questions Tags Users”,则变量的输出应类似于“SOQTU”
I'm looking for a way that I can extract the first letter of each word from an input field and place it into a variable.
Example: if the input field is "Stack-Overflow Questions Tags Users"
then the output for the variable should be something like "SOQTU"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
与 codaddict 相同,但更短
u
修饰符添加到正则表达式:preg_replace('...../u',
the same as codaddict's but shorter
u
modifier to regex:preg_replace('...../u',
类似于:
我使用正则表达式
\b(\w)
来匹配紧跟在单词边界后面的单词字符。编辑:
为了确保所有缩写字符都是大写,您可以使用
strtoupper
< /a> 如图所示。Something like:
I'm using the regex
\b(\w)
to match the word-char immediately following the word boundary.EDIT:
To ensure all your Acronym char are uppercase, you can use
strtoupper
as shown.只是为了完全不同:
Just to be completely different:
如果它们仅由空格
而没有其他东西分隔。您可以这样做:
If they are separated by only space
and not other things. This is how you can do it:
正则表达式匹配如 codaddict 上面所述,或 str_word_count() 以
1
作为第二个参数,返回找到的单词数组。请参阅手册中的示例。然后您可以以任何您喜欢的方式获取每个单词的第一个字母,包括substr($word, 0, 1)
Regular expression matching as codaddict says above, or str_word_count() with
1
as the second parameter, which returns an array of found words. See the examples in the manual. Then you can get the first letter of each word any way you like, includingsubstr($word, 0, 1)
str_word_count() 函数可能会执行您的操作寻找:
The str_word_count() function might do what you are looking for:
使用@codaddict 的答案。
我还认为在您有一个缩写词作为要缩写的词的情况下,例如DPR而不是开发石油资源,所以这样的词将在D上 作为缩写版本,没有多大意义。
using answer from @codaddict.
i also thought in a case where you have an abbreviated word as the word to be abbreviated e.g DPR and not Development Petroleum Resources, so such word will be on D as the abbreviated version which doesn't make much sense.
作为 @user187291 的
preg_replace()
模式的替代方案,这里具有相同的功能,无需在替换字符串中引用。它的工作原理是匹配第一个出现的单词字符,然后用
\K
忘记它,然后它将匹配零个或多个单词字符,然后它将匹配零个或多个非单词字符。这将消耗所有不需要的字符,只留下第一个出现的单词字符。这是理想的,因为不需要内爆匹配数组。u
修饰符确保正则表达式引擎将重音/多字节字符视为整个字符。代码:(演示)
输出:
As an alternative to @user187291's
preg_replace()
pattern, here is the same functionality without needing a reference in the replacement string.It works by matching the first occurring word characters, then forgetting it with
\K
, then it will match zero or more word characters, then it will match zero or more non-word characters. This will consume all of the unwanted characters and only leave the first occurring word characters. This is ideal because there is no need to implode an array of matches. Theu
modifier ensures that accented/multibyte characters are treated as whole characters by the regex engine.Code: (Demo)
Output: