Cómo obtener la primera palabra de una oración en PHP?


Quiero extraer la primera palabra de una variable de una cadena. Por ejemplo, tome esta entrada:

<?php $myvalue = 'Test me more'; ?>

La salida resultante debe ser Test, que es la primera palabra de la entrada. ¿Cómo puedo hacer esto?

Author: hippietrail, 2010-03-19

17 answers

Puede usar la función explode de la siguiente manera:

$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
 194
Author: codaddict,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-19 11:30:15

Hay una función de cadena (strtok) que se puede usar para dividir una cadena en cadenas más pequeñas (tokens) basadas en algunos separadores. Para los propósitos de este hilo, la primera palabra (definida como cualquier cosa antes del primer carácter de espacio) de Test me more se puede obtener mediante tokenizando la cadena en el carácter de espacio.

<?php
$value = "Test me more";
echo strtok($value, " "); // Test
?>

Para más detalles y ejemplos, vea la página de manual de strtok PHP.

 242
Author: salathe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-10 12:59:12

Si tiene PHP 5.3

$myvalue = 'Test me more';
echo strstr($myvalue, ' ', true);

Tenga en cuenta que si $myvalue es una cadena con una palabra strstr no devuelve nada en este caso. Una solución podría ser añadir un espacio a la cadena de prueba:

echo strstr( $myvalue . ' ', ' ', true );

Que siempre devolverá la primera palabra de la cadena, incluso si la cadena tiene solo una palabra

La alternativa es algo así como:

$i = strpos($myvalue, ' ');
echo $i !== false ? $myvalue : substr( $myvalue, 0, $i );

O usando explode, que tiene tantas respuestas usándolo que no me molestaré en señalar cómo hacerlo.

 35
Author: Yacoby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-07 00:48:20

Usted podría hacer

echo current(explode(' ',$myvalue));
 21
Author: AntonioCS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-19 11:29:25

Aunque es un poco tarde, PHP tiene una mejor solución para esto:

$words=str_word_count($myvalue, 1);
echo $words[0];
 9
Author: Lakshmi Rawat Singhania,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-21 06:38:21

En caso de que no esté seguro de que la cadena comienza con una palabra...

$input = ' Test me more ';
echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test
 5
Author: Lupuz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-17 12:57:26
<?php
  $value = "Hello world";
  $tokens = explode(" ", $value);
  echo $tokens[0];
?>

Simplemente use explode para obtener cada palabra de la entrada y la salida del primer elemento de la matriz resultante.

 4
Author: Ulf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-19 11:29:22

Usando la función split también puede obtener la primera palabra de la cadena.

<?php
$myvalue ="Test me more";
$result=split(" ",$myvalue);
echo $result[0];
?>
 4
Author: rekha_sri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-20 04:52:42

Similar a la respuesta aceptada con un paso menos:

$my_value = 'Test me more';
$first_word = explode(' ',trim($my_value))[0];

//$first_word == 'Test'
 4
Author: wheelmaker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 18:09:15

strtok es más rápido que extract o preg_* funciones.

 3
Author: HM2K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-29 18:30:37

Personalmente strsplit / explode / strtok no admite límites de palabras, por lo que para obtener una división más precisa, use la expresión regular con \w

preg_split('/[\s]+/',$string,1);

Esto dividiría las palabras con límites a un límite de 1.

 2
Author: RobertPitt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-13 15:21:29
$input = "Test me more";
echo preg_replace("/\s.*$/","",$input); // "Test"
 1
Author: markcial,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-19 11:32:57
$string = ' Test me more ';
preg_match('/\b\w+\b/i', $string, $result); // Test
echo $result;

/* You could use [a-zA-Z]+ instead of \w+ if wanted only alphabetical chars. */
$string = ' Test me more ';
preg_match('/\b[a-zA-Z]+\b/i', $string, $result); // Test
echo $result;

Saludos, Ciul

 1
Author: Ciul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-09 14:12:49
public function getStringFirstAlphabet($string){
    $data='';
    $string=explode(' ', $string);
    $i=0;
    foreach ($string as $key => $value) {
        $data.=$value[$i];
    }
    return $data;
}
 1
Author: RafayAhmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-27 09:36:00
$str='<?php $myvalue = Test me more; ?>';
$s = preg_split("/= *(.[^ ]*?) /", $str,-1,PREG_SPLIT_DELIM_CAPTURE);
print $s[1];
 0
Author: ghostdog74,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-19 11:51:05

Función que tokenizará la cadena en dos partes, la primera palabra y la cadena restante.

Valor devuelto: Tendrá first y remaining clave en $return matriz respectivamente. la primera comprobación strpos( $title," ") !== false es obligatoria en caso de que la cadena tenga solo una palabra y no haya espacio en ella.

function getStringFirstWord( $title ){

    $return = [];

    if( strpos( $title," ") !== false ) {

        $firstWord = strstr($title," ",true);
        $remainingTitle = substr(strstr($title," "), 1);

        if( !empty( $firstWord ) ) {
            $return['first'] = $firstWord;
        }
        if( !empty( $remainingTitle ) ) {
            $return['remaining'] = $remainingTitle;
        }
    }
    else {
        $return['first'] = $title;
    }

    return $return;
}
 0
Author: Shahzaib Hayat Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-25 07:17:38

Puede hacerlo usando la función de cadena de PHP substr sin convertir la cadena en una matriz.

 $string = 'some text here';
 $stringLength= strlen($string);
 echo ucfirst(substr($string,-$stringLength-1, 1));

/ / salida S

 0
Author: Afraz Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 12:49:18