Jagrati
Jagrati

Reputation: 12222

Split a string at last occurrence of a particular character string REGEX

I have a string:

buynaturallesunfloweroil1ltrat78rupees

now this string have two occurrences of at. I want to split the string atgetorlast occurrence of at.`

Some strings can be like buynaturallesunfloweroilget1ltrat78rupees

buynaturallesunfloweroil1ltrat78rupees.

I want to split the string such that:

Arr[0] = buynaturallesunfloweroil1ltr

Arr[1] = 78rupees

Basically I have to split the string at last occurence of at. I am not very good at preg_split.

Thanks in advance.

Upvotes: 1

Views: 1210

Answers (4)

prakash tank
prakash tank

Reputation: 1267

Sorry for my above answer. it was not fully functional:

here find the answer :

$str = "buynaturallesunfloweroil1ltrat78rupees";
echo $first = substr($str, 0, strrpos($str, 'at')); echo '---';
echo $second = substr($str, strrpos($str, 'at') + 2);

Upvotes: 1

Rahul
Rahul

Reputation: 18557

Here is the code :

$str = "buynaturallesunfloweroil1ltrat78rupees";
$arr = explode('at', $str);
print_r(end($arr));

I hope this will help

Upvotes: 1

prakash tank
prakash tank

Reputation: 1267

Try this :

<?php
 $str = "buynaturallesunfloweroil1ltrat78rupees";

echo $filename = substr($file, 0, strrpos($str, 'at')); echo '---';
echo $extension = substr($file, strrpos($str, 'at') + 2);

?>

Upvotes: 1

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

Try this:

(.*)at(.*)
  1. You get Arr[0] in group 1
  2. Arr1 in group 2

Explanation

Sample Code:

<?php

$re = '/(.*)at(.*)/s';
$str = 'buynaturallesunfloweroil1ltrat78rupees';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

?>

Upvotes: 1

Related Questions