PHP Find and replace after in a string? - php

I have some strings which contain the words LIMIT 3, 199 or LIMIT 0, 100.
Basically I want to replace the word LIMIT and everything after it in my string.
How do I do this in PHP? str_replace only replaces an item and the LIMIT text after is dynamic/
So it could be
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT LIMIT, 121
// RETURN WOULD BE
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT
WHEN JOHN TRIED LIMIT 343, 333 HE FOUND
// RETURN WOULD BE
WHEN JOHN TRIED

Use strpos to find the position of LIMIT within the string, and then use substr to return the string up until that point. Really pretty basic string manipulation.
Or perhaps use preg_replace if you want a one-liner, though I don't think going to the regex toolchest is needed here.

Replace out LIMIT.+$ using preg_replace with pattern /LIMIT.+$/m
That is to say:
$string = preg_replace("/LIMIT.+$/m","",$string);

Use strstr or stristr (case insensitive). Will work only for versions >= php 5.3.0
$str = strstr($your_string, 'LIMIT', true);

As I recommend against using regexes when you don't understand them, here's a simple answer that doesn't use them (do note, I do recommend learning regexes, but they aren't easy to learn):
$output = substr($input, 0, strpos($input, 'LIMIT'))

You can use strstr
$break = "LIMIT";
$array = array();
$array[] = "WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT LIMIT, 121";
$array[] = "WHEN JOHN TRIED LIMIT 343, 333 HE FOUND";
echo "<pre>";
foreach ( $array as $value ) {
echo strstr($value, $break, true), PHP_EOL;
}
Output
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT
WHEN JOHN TRIED

Related

How to split combined string

I have a string which looks like this:
21/04/2014,16:57:28,19,0,2021/04/2014,16:57:48,19,0,20
I would like to split it so that I get something like the following:
21/04/2014,16:57:28,19,0,20
21/04/2014,16:57:48,19,0,20
I have tried using php's substr which I thought was giving results but it duplicated this '21/04/2014,16:57:48,19,0,20' twice.
$data3 = array(substr($data1, -27), substr($data1, 27));
Even tried a regex with no luck.
If length of parts you want to get is constant you can use str_split function with second parameter.
$data = str_split($string, 27);
Elon Than's answer is the perfect solution if, as he states, the length is constant. However, I just thought I'd add this solution in case (for example) the '19' could also be '3' (or whatever):
preg_match_all("/\d{2}\/\d{2}\/\d{4}\,\d{2}:\d{2}:\d{2},\d{1,2},\d{1},\d{2}/", $string, $matches);
var_dump($matches[0]);
Notice the \d{1,2} will include any number that is 1 or 2 digits.
$data3 = array(substr($data1, 0, 27), substr($data1, 27));

How can I get number from a special string ? PHP

For example, 3 string are the following :
##7##
##563##
##120058##
How can I get those number like this :
echo first number is 7
echo second number is 563
echo third number is 120058
Thank you very much!
$numberAsString = trim($string, '##')
Is probably the easiest and fastest in this case. The output is still a string in this case, but in most cases that doesn't really matter. If it does in your case, you can use (int), (float) or the like to get it to the correct type.
Of course, regex would also be possible, e.g.:
$didMatch = preg_match('/#+([^#]+)#+/', $string, $matches);
Another possibility still is first extract the remaining part after the initial 2 # and then cast to a number, which seems to be always int in this case:
$number = (int)substr($string, 2);
Still another possibility would be to go by the count of the characters and just use substr like:
$numberAsString = substr($string, 2, -2);
Or you could be creative and use something like explode + implode + array functions:
$numberAsString = array_slice(explode('#', implode('', array_slice(explode('#', $string), 2))), 0, -2);
Of course, this last one is purely to show that it can be done in various ways, as it's very inefficient and impractical, but there are surely dozens of other ways.
In case you use this in a tight loop or somewhere where performance really matters, I would benchmark different possibilities - on a guess, I'd say that either the trim or the pure substring solution would be the fastest.
$str = "##563##";
preg_match("|\d+|", $str, $res);
print_r($res);
Just call the filter_var() function it will return the number only.
Whatever the input is, it will only filter the number for you!
filter_var("##120058##", FILTER_SANITIZE_NUMBER_INT) // return 120058
filter_var("*##20kkk", FILTER_SANITIZE_NUMBER_INT) // return 20

search in fread definition to find string

I have this:
$JunkHead3 = #fread($fp,180);
Echo "$JunkHead3", print this:
al-Arena # DeathMatchde_dust2cstrikeDust2 Only/dwÿÿÿÿDstoqn”;Bhtrl**7 !DEmesyhGBLo6ata7#CN3D0S3GA3M!73 | NestL3 L!oNà‘÷D{V
I need to search for /d and add +1 to print in this case "w"
How to do that ?
I try with array_search:
print(array_search('/d', $JunkHead3)+1);
but without success...
The array_search() function is for arrays, what you have is a string.
You can use strpos() to determine the position and substr() to extract the portion you need.
$index = strpos($JunkHead3, '/d');
$result = substr($JunkHead3, $index+2, 1);
http://www.php.net/manual/en/function.strpos.php
http://www.php.net/manual/en/function.substr.php
However I prefer using regular expressions, even though at first they seem a bit cryptic.
$result = preg_replace('/^.*\\/d(.).*$/', '$1', $JunkHead3);
http://php.net/manual/en/function.preg-replace.php

PHP : Get a number between 2 strings

I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.

splitting strings in php

I have some testcases/strings in this format:
o201_01_01a_Testing_to_see_If_this_testcases_passes:without_data
o201_01_01b_Testing_to_see_If_this_testcases_passes:data
rx01_01_03d_Testing_the_reconfiguration/Retest:
Actually this testcase name consists of the actual name and the description.
So, I want to split them like this :
o201_01_01a Testing_to_see_If_this_testcases_passes:without_data
o201_01_01b Testing_to_see_If_this_testcases_passes:data
rx01_01_03d Testing_the_reconfiguration/Retest:
I am unable to figure out the exact way to do this in explode in php
Can anyone help please?
Thanks.
If the first part has always the same length, why don't you use substr, e.g.
$string = "o201_01_01a_Testing_to_see_If_this_testcases_passes:without_data";
$first_part = substr($string, 0, 11); // o201_01_01a
$second_part = substr($string, 12); // Testing_to_see_If_this_testcases_passes:without_data
$results = preg_split("/([a-z0-9]+_[0-9]+_[0-9]+[a-z])(.*)/", $input);
That should give you an array of results, provided I got the regular expression correct.
http://www.php.net/manual/en/function.preg-split.php
Looking at the pattern, it appears that you need to use regular expressions. If this is how they all are, you can cut off the beginning by looking for an upper case character. The code might look like this:
$matches = array()
preg_match('/^[^A-Z]*?/', $string, $matches);
$matches = substr($matches[0], 0, count($matches[0])-1);
Would put the first little part into $matches. Working on second part...

Categories