flochristos
flochristos

Reputation: 75

Getting STRING Characters value before a character occuring more than once in php

I want to get the value of the last word from a varaible.....

if the variable has a content of ,book,farm,chop,cook

i want to get the value of cook alone after the last , in php

$valt = ",book,farm,chop,cook";

or to get the value from the right hand side before a ',' is encountered... Thanks

Upvotes: 0

Views: 75

Answers (4)

Swetha Sekar
Swetha Sekar

Reputation: 237

Use explode() to convert from string to array and use end().

   <?php
   $arr = ",book,farm,chop,cook";
   $a = explode(',', $arr);
   print_r(end($a));

Upvotes: 3

u_mulder
u_mulder

Reputation: 54841

Optional solution with strrpos which finds position of last occurence of ,. After that you can use substr to get a substring starting from the next position:

$str = ",book,farm,chop,cook";
print_r(substr($str, 1 + strrpos($str, ',')));

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94662

Using strrchr() and a ltrim() to tidy up you could do this

$valt = ",book,farm,chop,cook";
echo ltrim(strrchr($valt,','),',');

Result

cook

Upvotes: 1

zemrin
zemrin

Reputation: 27

$valt = ",book,farm,chop,cook";
$r = explode(",",$valt);
$a = array_key_last($r);
print_r($a);

Upvotes: -2

Related Questions