주어진 문자열에 대해 각 단어의 첫 글자를 어떻게 얻습니까?
$string = "Community College District";
$result = "CCD";
나는 자바 스크립트 방법을 찾았지만 그것을 PHP로 변환하는 방법을 모르겠습니다.
주어진 문자열에 대해 각 단어의 첫 글자를 어떻게 얻습니까?
$string = "Community College District";
$result = "CCD";
나는 자바 스크립트 방법을 찾았지만 그것을 PHP로 변환하는 방법을 모르겠습니다.
What__about__this__sentence?또는What about.This sentence?
답변:
explode()공백 []에서 결과 문자열에 배열로 액세스 하기 위해 표기법을 사용합니다 .
$words = explode(" ", "Community College District");
$acronym = "";
foreach ($words as $w) {
$acronym .= $w[0];
}
여러 개의 공백이 단어를 구분할 수 있다고 예상되는 경우 대신 preg_split()
$words = preg_split("/\s+/", "Community College District");
또는 공백 이외의 문자가 단어 ( -,_)를 구분하는 경우 다음도 사용하십시오 preg_split().
// Delimit by multiple spaces, hyphen, underscore, comma
$words = preg_split("/[\s,_-]+/", "Community College District");
preg_match_all("/[A-Z]/", ucwords(strtolower($string)), $matches);
이를 수행하는 가장 좋은 방법은 정규식을 사용하는 것입니다.
원하는 것을 논리적으로 분석 할 수 있습니다. 문자열의 모든 문자가 단어의 시작 부분에 있기를 원합니다. 이러한 문자를 식별하는 가장 좋은 방법은 앞에 공백이있는 문자를 찾는 것입니다.
따라서 해당 공백 문자에 대한 룩 비하인드 로 시작하고 그 뒤에 임의의 문자가 있습니다.
/(?<=\s)./
공백이 앞에 오는 모든 문자를 찾습니다. 그러나-문자열의 첫 번째 문자는 추출하려는 문자열의 문자입니다. 그리고 문자열의 첫 번째 문자이기 때문에 앞에 공백이 올 수 없습니다. 따라서 문자열에서 공백 이나 첫 번째 문자가 앞에 오는 모든 항목을 일치 시키려고 하므로 주제 시작 어설 션을 추가합니다 .
/(?<=\s|^)./
이제 우리는 가까워지고 있습니다. 그러나 문자열에 여러 공백 블록이 포함되어 있으면 어떻게 될까요? 공백과 구두점 문자가 있으면 어떻게됩니까? 우리는 아마 그것들 중 어느 것과도 일치하고 싶지 않을 것입니다. 지방에서 우리는 아마도 문자와 일치시키고 싶을 것입니다. 캐릭터 클래스 를 사용하여 할 수 있습니다 [a-zA-Z]. 그리고 i 수식어를 사용하여 대소 문자를 구분하지 않는 표현식을 만들 수 있습니다 .
따라서 우리는 다음과 같이 끝납니다.
/(?<=\s|^)[a-z]/i
그러나 실제로 이것을 PHP에서 어떻게 사용합니까? 우리 는 문자열 내에서 모든 정규 표현식 을 일치 시키고 싶으 므로 다음을 사용합니다 preg_match_all().
$string = "Progress in Veterinary Science";
$expr = '/(?<=\s|^)[a-z]/i';
preg_match_all($expr, $string, $matches);
이제 추출하려는 모든 문자가 있습니다. 표시 한 결과 문자열을 구성하려면 다시 결합해야합니다 .
$result = implode('', $matches[0]);
... 그리고 우리는 그것들이 모두 대문자 인지 확인해야합니다 :
$result = strtoupper($result);
그리고 그게 전부입니다.
(?<=\b)대신에 (?<=\s|^), 이것은 당신이 단어의 첫 글자는 하이픈, 마침표 등으로 구분 캡처 할 것입니다 (기본적으로 "비 단어"문자 또는 \ W \ w에 일치하지 않을 것), 하지만 원하지 않는 것을 캡처하게 될 수도 있습니다.
단어가 모두 공백으로 분리되어 있다고 가정하면 다음과 같은 적절한 솔루션이됩니다.
$string = "Progress in Veterinary Science";
function initials($str) {
$ret = '';
foreach (explode(' ', $str) as $word)
$ret .= strtoupper($word[0]);
return $ret;
}
echo initials($string); // would output "PIVS"
substr($word,0,1)(또는 실제로- mb_substr($word, 0, 1, 'utf-8'))이 절대적으로 필요합니다. simple $word[0]을 사용하면 멀티 바이트 문자의 절반이 잘리고 잘못된 이니셜 (실제 문자 대신 이상한 기호)이 표시됩니다. 이 상황을 오류라고 부르면 답이 있습니다! :]
많은 explode답변이 있습니다. 이 strtok함수를 사용하는 것이 훨씬 더 우아하고 메모리 효율적인 솔루션 이라고 생각 합니다.
function createAcronym($string) {
$output = null;
$token = strtok($string, ' ');
while ($token !== false) {
$output .= $token[0];
$token = strtok(' ');
}
return $output;
}
$string = 'Progress in Veterinary Science';
echo createAcronym($string, false);
다음은 UTF8 문자와 대문자 단어 만 사용하는 옵션을 지원하는보다 강력하고 유용한 함수입니다.
function createAcronym($string, $onlyCapitals = false) {
$output = null;
$token = strtok($string, ' ');
while ($token !== false) {
$character = mb_substr($token, 0, 1);
if ($onlyCapitals and mb_strtoupper($character) !== $character) {
$token = strtok(' ');
continue;
}
$output .= $character;
$token = strtok(' ');
}
return $output;
}
$string = 'Leiðari í Kliniskum Útbúgvingum';
echo createAcronym($string);
explode이 문제를 해결하기 위해 사용 하는 것을 순진한 솔루션 이라고합니다 . 구현하기 쉽기 때문에 버블 정렬 알고리즘을 사용하는 것과 같습니다.
foreach(explode(' ', $string) as $word) echo $word[0];. 한눈에 이해하기 쉽고 시간 낭비가 아닙니다.
explode이 잘못되었다고 말하는 것이 아니라 문제를 해결하는 더 우아한 발언이있다. 그리고 저는 "우아함"이라는 단어를 미학적으로 사용하지 않고 기술적 인 방식으로 사용하고 있습니다.
Michael Berkowski (및 기타) 답변, 한 줄로 단순화되고 멀티 바이트 문자에서 올바르게 작동합니다 (즉, 라틴어가 아닌 문자열에서 약어 / 이니셜 만들기).
foreach(explode(' ', $words) as $word) $acronym .= mb_substr($word, 0, 1, 'utf-8');
사용 mb_substr($word, 0, 1, 'utf-8')하는 대신 $word[0]UTF-8로 인코딩 된 문자열을 사용할 때, 즉 비 라틴, 멀티 바이트 문자열과 문자, 작업을하는 경우, 반드시 것 같다.
이렇게
preg_match_all('#(?<=\s|\b)\pL#u', $String, $Result);
echo '<pre>' . print_r($Result, 1) . '</pre>';
<=?
\pL. 그래도 약간의 설명을 추가해 주시겠습니까? 나는 ;-) 단지 그에게 일을주는 것보다 물고기 사람을 가르치는 것을 선호
다른 사람들이 설명했듯이 고전적인 방법은 초기 문자열의 각 단어를 반복하고 단어를 첫 글자로 줄이고 첫 글자를 함께 결합하는 것입니다.
다음은 여러 단계를 결합한 도우미 메서드입니다.
/**
* @return string
*/
function getInitials($string = null) {
return array_reduce(
explode(' ', $string),
function ($initials, $word) {
return sprintf('%s%s', $initials, substr($word, 0, 1));
},
''
);
}
주의 : 주어진 문자열이 비어있는 경우 빈 문자열을 반환합니다.
getInitials('Community College District')
문자열 'CCD'(길이 = 3)
getInitials()
문자열 ''(길이 = 0)
getInitials('Lorem ipsum dolor sic amet')
문자열 'Lidsa'(길이 = 5)
물론 array_reduce()예 strtoupper()를 들어 대문자 이니셜 만 선호하는 경우 와 같이 의 콜백 함수에 필터를 추가 할 수 있습니다 .
내가 요리 한 것.
/**
* Return the first letter of each word in uppercase - if it's too long.
*
* @param string $str
* @param int $max
* @param string $acronym
* @return string
*/
function str_acronym($str, $max = 12, $acronym = '')
{
if (strlen($str) <= $max) return $str;
$words = explode(' ', $str);
foreach ($words as $word)
{
$acronym .= strtoupper(substr($word, 0, 1));
}
return $acronym;
}
str_word_count 함수를 사용하지 않는 이유는 무엇 입니까?
해당 배열을 첫 글자로 줄 입니다.
$ acronym = array_reduce (str_word_count ( "Community College District", 1), function ($ res, $ w) {return $ res. $ w [0];});
폭발해서 다시 합류해야 할 것 같아요 .....
<?php
$string = "Progress in Veterinary Science";
$pieces = explode(" ", $string);
$str="";
foreach($pieces as $piece)
{
$str.=$piece[0];
}
echo $str; /// it will result into "PiVS"
?>
Prateeks 재단을 사용하여 설명이 포함 된 간단한 예가 있습니다.
// initialize variables
$string = 'Capitalize Each First Word In A String';
$myCapitalizedString = '';
// here's the code
$strs=explode(" ",$string);
foreach($strs as $str) {
$myCapitalizedString .= $str[0];
}
// output
echo $myCapitalizedString; // prints 'CEFWIAS'
입력 문자열에서 두 글자 사이에 더 많은 공백이 있으면 이것을 시도하십시오.
function first_letter($str)
{
$arr2 = array_filter(array_map('trim',explode(' ', $str)));
$result='';
foreach($arr2 as $v)
{
$result.=$v[0];
}
return $result;
}
$str=" Let's try with more spaces for fun . ";
echo first_letter($str);
동일한 코드의 대안
function first_letter($str)
{
return implode('', array_map(function($v) { return $v[0]; },array_filter(array_map('trim',explode(' ', $str)))));;
}
$str=" Let's try with more spaces for fun . ";
echo first_letter($str);
큰 문자열 (또는 파일에서 직접) explode()에서이 작업을 수행하는 경우이를 수행하는 가장 좋은 방법이 아닙니다. 2MB 큰 문자열을 메모리로 분할해야하는 경우 얼마나 많은 메모리가 낭비 될지 상상해보십시오.
조금 더 코딩하고 (가정하면 PHP >= 5.0) Iterator정확하게 이것을 수행 하는 PHP의 클래스를 쉽게 구현할 수 있습니다 . 이것은 파이썬의 생성기에 가깝고 짧게 짧게 코드는 다음과 같습니다.
/**
* Class for CONTINOUS reading of words from string.
*/
class WordsIterator implements Iterator {
private $pos = 0;
private $str = '';
private $index = 0;
private $current = null;
// Regexp explained:
// ([^\\w]*?) - Eat everything non-word before actual word characters
// Mostly used only if string beings with non-word char
// ([\\w]+) - Word
// ([^\\w]+?|$) - Trailing thrash
private $re = '~([^\\w]*?)([\\w]+)([^\\w]+?|$)~imsS';
// Primary initialize string
public function __construct($str) {
$this->str = $str;
}
// Restart indexing
function rewind() {
$this->pos = 0;
$this->index = 0;
$this->current = null;
}
// Fetches current word
function current() {
return $this->current;
}
// Return id of word you are currently at (you can use offset too)
function key() {
return $this->index;
}
// Here's where the magic is done
function next() {
if( $this->pos < 0){
return;
}
$match = array();
++$this->index;
// If we can't find any another piece that matches... Set pos to -1
// and stop function
if( !preg_match( $this->re, $this->str, $match, 0, $this->pos)){
$this->current = null;
$this->pos = -1;
return;
}
// Skip what we have read now
$this->current = $match[2];
$this->pos += strlen( $match[1]) + strlen( $match[2]) + strlen($match[3]);
// We're trying to iterate past string
if( $this->pos >= strlen($this->str)){
$this->pos = -1;
}
}
// Okay, we're done? :)
function valid() {
return ($this->pos > -1);
}
}
좀 더 까다로운 문자열에 사용할 경우 :
$a = new WordsIterator("Progress in Veterinary Science. And, make it !more! interesting!\nWith new line.");
foreach( $a as $i){
echo $i;
echo "\n";
}
예상 결과를 얻을 수 있습니까?
Progress
in
Veterinary
Science
And
make
it
more
interesting
With
new
line
따라서 $i[0]첫 글자를 가져 오는 데 쉽게 사용할 수 있습니다. 전체 문자열을 메모리로 분할하는 것보다 더 효과적인 솔루션임을 알 수 있습니다 (항상 가능한 적은 메모리 만 사용). 이 솔루션을 쉽게 수정하여 파일 등을 지속적으로 읽을 수도 있습니다.
<?php $arr = explode(" ",$String);
foreach($arr as $s)
{
echo substr($s,0,1);
}
?>
먼저 공백으로 문자열을 분해 한 다음 첫 번째 문자를 substr합니다.
이 시도
function initials($string) {
if(!(empty($string))) {
if(strpos($string, " ")) {
$string = explode(" ", $string);
$count = count($string);
$new_string = '';
for($i = 0; $i < $count; $i++) {
$first_letter = substr(ucwords($string[$i]), 0, 1);
$new_string .= $first_letter;
}
return $new_string;
} else {
$first_letter = substr(ucwords($string), 0, 1);
$string = $first_letter;
return $string;
}
} else {
return "empty string!";
}
}
echo initials('Thomas Edison');
이 답변은 https://stackoverflow.com/a/33080232/1046909 이지만 멀티 바이트 문자열을 지원합니다.
if (!function_exists('str_acronym')) {
function str_acronym(string $str, int $min = -1, string $prefix = null): string
{
if (mb_strlen($str) <= $min) {
return $str;
};
$words = explode(' ', $str);
$acronym = strval($prefix);
foreach ($words as $word) {
if ($word = trim($word)) {
$acronym .= mb_strtoupper(mb_substr($word, 0, 1));
}
}
return $acronym;
}
}
@Michael Berkowski의 답변을 기반으로 해당 기능을 사용할 수 있습니다.
function buildAcronym($string, $length = 1) {
$words = explode(" ", $string);
$acronym = "";
$length = (self::is_empty($string) || $length <= 0 ? 1 : $length);
foreach ($words as $i => $w) {
$i += 1;
if($i <= $length) {
$acronym .= $w[0];
}
}
return $acronym;
}
$ length 매개 변수는 표시 할 문자 수를 결정합니다.
용법:
$acronym = buildAcronym("Hello World", 2);