PHP - How to get the string between two specific characters - php

I got now a two sides that contains numbers and between two specific numbers there is a string that shows a group of numbers, Let's say we got this 123456789$numbers1234567 and I want to get the result of $numbers so how can I get it?
Thanks

If you know the two strings that it is sandwiched between then you can strip out the strings that you are looking for.
Not too elegant but this works:
$str1 = "123456789";
$str2 = "1234567";
$numberstr = "123456789";
$searchstring = "123456789".$numberstr."1234567";
$limit = 1;
$numbers = substr($searchstring, 0, strlen($searchstring) - strlen($str2)); // Remove the end of the string with length = $str2
$numbers = substr($numbers, strlen($numbers) - strlen($str1)); // Remove the most string from the beginning
print $numbers;
Output:
123456789
In summary, it removes the known string from the end, then the other known string from the beginning.
UPDATE: as per the comments, use two substrs to find the wanted string

Related

PHP: remove last comma of a multipolygon

I have following issue:
I import WKT dynamicaly from DB into WKT Wicket Javascript library. I must do some substitutions to fit the WKT correctly. Since mysql fetches WKT AsText(SHAPE) i recive several arrays e.g. POLYGON((xxxx)),POLYGON((yyyy)) and so on.
First, I had to remove all "POLYGON" doing
$str = preg_replace('/^POLYGON/', '', $WKT[1]);
and add MULTIPOLYGON before <?php
tag in the wicket. It works.
Second, I must add comma between polygons, preicisely between "))((" brackets:
$str2 = str_replace(array('((', '))'), array('((', ')),'), $str);
It works but last comma remains what "slightly" deforms my multipolygon:
MULTIPOLYGON((xxx)),((yyy)),((zzz)),
How can I remove last comma?
I would be thankful for every regex or some other solution which can solve my problem.
In any string, you can remove the last X if you are sure that no X follows. So, you can use a negative lookahead: (,)(?!.*,), as seen here and replace it with empty string.
$result = preg_replace('/(,)(?!.*,)/', '', $str)
This doesn't look at the context though, it will just remove the last comma of any string, no matter where it is.
Thank you both - your answers were right and very helpful.
The problem was not string replacement. It was more the data fetching from DB.
Mysqli_fetch_array and mysqli_fetch_assoc return stringstringsring or arrayarrayarray for 3 rows fetched. That is why all commas were replaced.
I changed to mysqli_fetch_all ,then did minor replacements for each row (as array) and implode each one as variable. After i merged them into single variable, then I could apply your solutions. It is not sofisticated solution, but if it is packed into function it'll be fine.
($WKT = mysqli_fetch_all($result)) {
$str = preg_replace('/POLYGON/', '', $WKT[0]);
$str1 = preg_replace('/POLYGON/', '', $WKT[1]);
$str2 = preg_replace('/POLYGON/', '', $WKT[2]);
$str3 = implode($str);
$str4 = implode($str1);
$str5 = implode($str2);
$str6 = $str3 . $str4 . $str5;
$str7 = preg_replace('/\)\)/', ')),', $str6);
$str8 = rtrim($str7, ",");
echo $str8;
}

php - Get string before nth dash (-)

I have a string that looks something like this:
abc-def-ghi-jkl-mno-pqr-stu-vwx-yz I'd like to get the content BEFORE the 4th dash, so effectively, I'd like to get abc-def-ghi-jkl assigned to a new string, then I'd like to get mno assigned to a different string.
How could I go about doing this? I tried using explode but that changed it to an array and I didn't want to do it that way.
Try this:
$n = 4; //nth dash
$str = 'abc-def-ghi-jkl-mno-pqr-stu-vwx-yz';
$pieces = explode('-', $str);
$part1 = implode('-', array_slice($pieces, 0, $n));
$part2 = $pieces[$n];
echo $part1; //abc-def-ghi-jkl
echo $part2; //mno
See demo
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Can you add your source code? I done this one before but I cant remember the exact source code I used. But I am pretty sure I used explode and you can't avoid using array.
EDIT: Mark M answer is right.
you could try using substr as another possible solution
http://php.net/manual/en/function.substr.php
If I see where you are trying to get with this you could also go onto substr_replace
I guess an alternative to explode would be to find the position of the 4th - in the string and then get a substring from the start of the string up to that character.
You can find the position using a loop with the method explained at find the second occurrence of a char in a string php and then use substr(string,0,pos) to get the substring.
$string = "abc-def-ghi-jkl-mno-pqr-stu-vwx-yz";
$pos = -1;
for($i=0;$i<4;$i++)
$pos = strpos($string, '-', $pos+1);
echo substr($string, 0, $pos);
Code isn't tested but the process is easy to understand. You start at the first character (0), find a - and on the next loop you start at that position +1. The loop repeats it for a set number of times and then you get the substring from the start to that last - you found.

separate a string from some specific words in php

I have a string called $metar
$metar = EICK 011300Z 10004KT 27/17 Q1018 TEMPO AT0800 20006KT 010V220 9999 SCT029
and this string could changed every an hour depending a dynamic file.
in basic, i want to separate the $metar to two strings, the separate point is "AT0800"
list($a, $b) = explode(' AT0800 ', $metar);
echo $b;
but the problem is the "AT0800" could change to "AT1200" or "AT1900" in the future, the only words are keep is the "AT", So how can i get the string $b which is after the word "ATxxxx" ? Thanks
Split the string with AT#### using a regex:
$metar_split = preg_split('/AT[0-9]{4}/', $metar);
The first half:
echo trim($metar_split[0]);
The second half (the one you're looking for):
$b = trim($metar_split[1]);
To get the AT#### portion:
preg_match('/AT[0-9]{4}/', $metar, $matches);
$metar_at = $matches[0];
If the position of ATxxxx in the string is always fixed (and the number of characters before it are also fixed), and xxxx always means 4 digits, then you could just go and use substr to select the desired segment of the string, as in:
$part1 = substr($metar, 0, 38);
$part2 = substr($metar, 46);
However, if you are looking at a varying lengths for the rest of the content, yet ATxxxx format is expected, you could have at it with a regular expression along the lines of:
([\w\s\/]+) AT[0-9]{4} ([\w\s\/]+)
This will grab out your two parts, which are seperated by the letters AT and exactly 4 digits. The [\w\s\/]+ part says: "grab me word characters (letters and numbers), white spaces and slash characters at least one, or any number more".
here you go, the answer is attached below:
list($a, $b) = explode('AT', $metar, 2);
//echo $b;
list($c, $d) = explode(' ', $b, 2);
//echo $d;

php remove characters from string - at the same position from the last removed

I will start with an example to explain better what I mean. I have the following string:
$str = "x' OR firstname LIKE '%Carla%";
$returned_str = chunk_split($str,1,".");
echo $returned_str;
This string is being returned like this:
x.'. .O.R. .f.i.r.s.t.n.a.m.e. .L.I.K.E. .'.%.C.a.r.l.a.%.
So now what I am trying to do is to reverse what I did with chunk_split().
I want to remove the dots, but only the ones that are precedent of one character, and to do this successfully, the solution shouldn't remove original dots of the string.
So this string:
My name is Fábio. I like PHP. I am Portuguese.
In the end shouldn't end like this:
My name is Fábio I like PHP I am Portuguese
You can use str_split for convert your string to an array.
Then, you recreate your string in concatenating a char on two (modulo 2 for example).
Edit: or just :
$reverse = '';
for ($i=0; $i < strlen($returned_str); $i += 2)
$reverse .= $returned_str[$i];
you can use the explode function
$x=explode('.','your string here');//it returns an array

How to get a matching string by comparing 2 strings?

I was once asked a question in an interview that if we have 2 strings, how we can get a part of matching string from these two?
for example
$str1 = "My name is baig";
$str2 = "Baig is a nice person";
now i want the output
"i a e s g" and other matching letters
I want this in Php
Thanks in advance
this is code to get the expected result for two string str1 and str2
<?php
$str1 = strtolower("My name is baig");
$str2 = strtolower("Baig is a nice person");
$array1 = explode(' ',$str1);
$array2 = explode(' ',$str2);
$result = array_intersect($array2, $array1);
print_r(implode(' ',$result));
?>
Well you have several options...
If you want matches in a specific order, meaning is a string inside another string, you might go for strstr, if you want to find any common point between 2 strings, you might want to first find an explode pattern, in your case a space.
Expode both string and intersect both arrays.
You can use array_intersect after use the function explode on your string.
A working example :
http://codepad.org/IikNr2Vv
But this is case sensitive, Baig will be different of baig.
To resolve this, you can use the strtolower function to transform to lower cas all your string.
got the following answer from another forum
<?php
$str1 = "My name is baig";
$str2 = "Baig is a nice person";
$r1 = str_split(preg_replace("/[^a-zA-z]/","",strtolower($str1)));
$r2 = str_split(preg_replace("/[^a-zA-z]/","",strtolower($str2)));
$match = array_unique(array_intersect($r1,$r2));
$match = implode(" ",$match);
echo "Matched letters are: ".$match;
?>
Case sensitivity is still an issue but i will go through it

Categories