0
votes

I am trying to get the 5th word from a title to use it as a breadcrumb path. Also it need to print until meet special character like , or ( like here:

Ex: Lorem ipsum dolor sit Amet, consectetur adipiscing elit

Result: Amet

current(explode(',', get_the_title( $post->ID )));
2
When you say, "print until meet special character", do you mean any character that is not alphanumeric? - blupointmedia
please provide some specific examples of inputs and expected results - AD7six
Yes, but in this case It only need - , ( [ - tw8sw8dw8
When I use current(explode(' ', I get the first word only. What have to be to get the fifth? - tw8sw8dw8
@tw8sw8dw8, can you please give feedback and/or accept if any of the answers below worked for you? - blupointmedia

2 Answers

0
votes

You can first explode your string separated by space ' '. From the array you get after this, the 4th index will contain your 5th word. Using str_replace you can replace the comma in your 5th word and you will get the output Amet

$myvalue = 'Lorem ipsum dolor sit Amet, consectetur adipiscing elit';
$arr = explode(' ',trim($myvalue));
echo $arr[4]; // get 5th word 
$str = str_replace( ',', '', $arr[4] ); 
// Display the  string separated from comma
echo($str); 
0
votes

Here is a function that will get you any word position with a list of chars you want to stop at.

$str = 'Lorem ipsum dolor sit Amet, consectetur adipiscing elit';

echo getNthWord($str, ' ', 5, [',','(','[']);

function getNthWord($input, $delimiter, $numWord, $replaceChars = []) {
  $split = explode($delimiter, $input);
  $word = $split[ $numWord - 1 ];

  return str_replace($replaceChars, '', $word);
}