2

I use some mysql queries to retrieve data from a Jdatabase table as strings. Now I need to find the part of that string which doesn't match another string (which actually is a sub-string of the main string). Its a bit confusing, but the below example will make it easy to understand.

Main String : 23/CSE/4/2014

Sub-String : /CSE/4/2014

Required Output : 23

What would be the best way according to Joomla coding standards to achieve this?

2 Answers 2

1

If the string will always be separated by forward slashes and you want to get the first value, you could explode into an array like so:

$string = '23/CSE/4/2014';
$array = explode('/', $string);

echo $array[0]; // 23
echo $array[1]; // CSE
echo $array[2]; // 4
echo $array[3]; // 2014
3
  • worked like charm!
    – saibbyweb
    Aug 22, 2016 at 15:49
  • @Saibbyweb - Good good :) You could also use a Regex but I'm crap at them.
    – Lodder
    Aug 22, 2016 at 15:52
  • I don't think I would require RegEx :) You have answered 80% of my questions on JSE, thanks a million.
    – saibbyweb
    Aug 22, 2016 at 15:59
0

You haven't offered any details into the variability of your input strings, so we can only assume the challenges that you may be facing.

If your sub_string is always on the right side of the value that you wish to isolate, then this will do:

Demo

$main_string = "23/CSE/4/2014";
$sub_string = "/CSE/4/2014";
echo str_replace($sub_string, '', $main_string);
// 23

If the value to be isolated may exist on either side of the sub_string, then this will do the job:

Demo

$main_string = "23/CSE/4/2014";  // or "CSE/4/2014/23"
$sub_string = "CSE/4/2014";  // notice no leading/trailing slash on this value
echo trim(str_replace($sub_string, '', $main_string), '/');  // leading/trailing slashes are trimmed
// 23

If the value to be isolated may be nested inside of the substring's slash delimited values, then you have a more complicated challenge to contend with and a rethink about data formatting may be in order.

Exploding your main_string and sub_string then making iterated comparisons (or an array_diff() call) to filter the individual values is going to be heavy-handed and/or potentially damaging. If the desired value is the same as one of the sub_string slash-delimited values, you will lose what you are trying to find.

p.s. Since this question is tagged with mysql for some reason, I'll offer the MySQL equivalent of my first snippet:

Demo

SELECT REPLACE('23/CSE/4/2014', '/CSE/4/2014', '')
// 23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.