John Davidson

php - get only the second word


When i was parsing (simple html dom.php), I encountered the following problem, when receiving the final data, I need to get only the second word(Barcelona) from the given string.

<h1 class="entry-title">Taxi Barcelona</h1>

On the stack overflow, I found a couple of similar problems, but I would like to analyze this particular case, since using ready-made methods I did not come to success

I already tried this code

  $town = $html->find('h1.entry-title', 0);
$town_name = $town;
$t_name = stripos($town_name, ' ');
echo substr($town_name, 10);

But it was unsuccessful for my case because it gave the following line:
"entry-title">Taxi Barcelona

Can anyone lend me a helping hand?

My Answer:
You can achieve this by using the explode function in PHP to split the string into an array of words and then accessing the second element of the array. Here's an example code snippet to get the second word from the given string:

$string = "I love Barcelona FC";
$words = explode(" ", $string);

if(count($words) >= 2) {
$secondWord = $words[1];
echo $secondWord; // Output: Barcelona
} else {
echo "String does not have enough words";

In this code snippet, we first split the string into an array of words using the explode function with a space as the delimiter. Then, we check if the array has at least two elements (to ensure there is a second word) and finally, we access and output the second word.

Rate this post

3 of 5 based on 8150 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us