1

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.

4
  • 2
    strrpos is enough. Commented Dec 14, 2016 at 6:51
  • would you please give me an example of that. Commented Dec 14, 2016 at 6:51
  • See here stackoverflow.com/questions/3835636/… Commented Dec 14, 2016 at 6:51
  • 2
    Or explode() ...... Commented Dec 14, 2016 at 6:52

4 Answers 4

1

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);

?>
Sign up to request clarification or add additional context in comments.

5 Comments

and the reason is ?
preg_split("/(.*)at(.*)/", "buynaturallesunfloweroil1ltrat78rupees"); is giving me empty array.
what if I want only arr[0] and arr[1]. $matches give me actually array of size 3.
No, as it will break at each instance of 'at'
if you don't understand how regex thing work, then you need to know that, index zero contains the full match (full string) , and then comes the capture groups which is group 1 and 2
1

Try this :

<?php
 $str = "buynaturallesunfloweroil1ltrat78rupees";

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

?>

1 Comment

what is $file here ? and $extension ?
1

Here is the code :

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

I hope this will help

Comments

1

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);

3 Comments

you've posted 2 identical answers(by approach), why?
@RomanPerekhrest : the frist answer was not right and the naming convenstions were not proper.
so remove the improper one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.