PHP convert string to array with variable element length - php

I have a string AB0512CD123456 and using preg match how can I convert it to
Array[0]='AB';
Array[1]='05';
Array[2]='12CD12';
Array[3]='3456';
That is first element with size-2,then 2,6,4 etc.The input string may be dynamic.

If the input string length is fixed, all you need is sscanf():
var_dump(sscanf('AB0512CD123456', '%2s%2s%6s%4s'));
Output:
array(4) {
[0]=>
string(2) "AB"
[1]=>
string(2) "05"
[2]=>
string(6) "12CD12"
[3]=>
string(4) "3456"
}

Better use this:
$str="AB0512CD123456";
$Array[0] = substr($str, 0,2);
$Array[1] = substr($str, 2,2);
$Array[2] = substr($str, 4,6);
$Array[3] = substr($str, 10,4);

Works on any generalized pattern
This example makes use of sscanf as proposed by Paulo Freitas
<?php
$str="AB0512CD123456";
$pattern="2,3,4,5"; // Your pattern
$pattern=explode(",",$pattern);
foreach($pattern as $k=>$v)
{
$newpattern.="%".$v."s";
}
var_dump(sscanf($str,$newpattern));

Related

numbers and next line only in the textarea field

I m trying to use following pattern
65465465465654
6546465465465465
5646545646464
6545646456
6454646456
in text area
please anyone help me
to check preg_match pattern
for the above input type
I want to take mobile numbers separated by the next line character.
Try this:
$numbers = "65465465465654
6546465465465465
5646545646464
6545646456
6454646456";
preg_match_all("/([0-9]*)\n/", $numbers, $resultArray);
foreach ($resultArray as $result) {
preg_replace("/\n/", "", $result);
}
Output:
array(4) {
[0]=>
string(14) "65465465465654"
[1]=>
string(16) "6546465465465465"
[2]=>
string(13) "5646545646464"
[3]=>
string(10) "6545646456"
}

PHP regex preg_grep change string path

I have array:
$array = array(
"C:/path/something1/something2/dir",
"C:/path1/something/something2/dir2\nextdir",
"C:/path2/something/dir2\nextdir\next",
"C:/path/something3/something6/something7/dir5\nextdir2\next"
);
All that is before the last sign "/" with him to disappear.
I want something like that:
$array = array(
"dir",
"dir2\nextdir",
"dir2\nextdir\next",
"dir5\nextdir2\next"
);
I need regex
$new_array = preg_grep("/regex/", $array);
I have no idea how to write a regex.
I dont want like that:
foreach($array as $key => $val) {
$e = explode("/", $val);
$new_array[] = end($e);
}
preg_grep() does not change/replace the values, it returns the items that match the given regular expression. If you must use regex and replace the values, take a look at preg_replace() instead:
$array = preg_replace('~.*/~', '', $array);
var_dump($array);
Output
array(4) {
[0]=> string(3) "dir"
[1]=> string(12) "dir2\nextdir"
[2]=> string(17) "dir2\nextdir\next"
[3]=> string(18) "dir5\nextdir2\next"
}

Using PHP explode to create an array of words from $_GET

I'm having trouble using explode() in php.
I want to make an array of strings from the $_GET super global array.
The url will be like:
example/myproject.php?keywords=this+is+an+example
I want an array of the keywords so it should be like this:
myArray(6) = { [0]=> string(4) "this"
[1]=> string(2) "is"
[2]=> string(2) "an"
[3]=> string(7) "example" }
Here's my code:
$stringVals = explode("+",($_GET['keywords']));
var_dump($stringVals);
Here's the output:
array(1) { [0]=> string(30) "this is an example of a string" }
An example that works:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
var_dump($pieces);
The output of this:
array(6) { [0]=> string(6) "piece1" [1]=> string(6) "piece2" [2]=>
string(6) "piece3" [3]=> string(6) "piece4" [4]=> string(6) "piece5"
[5]=> string(6) "piece6" }
I want the words from $_GET like that..
The "+" sign you see is actually just an encoded space. Therefore, you can split it normally using a space.
explode(' ', $_GET['keywords']);
Make sure you sanitize it if you're going to put it in a database.
Actually you can simply use:
explode(" ", $_GET['string'])
The + sign in the url actually means a space, not plus :- )
It's because spaces aren't allowed in the urls (url cannot have whitespaces), so it's actually converted to a plus sign.
In a normal GET request, the + in the URL will be converted back to spaces by the web server, so you should be exploding on ' '.
$stringVars = explode(' ', $_GET['keywords']);
See https://stackoverflow.com/a/2678602/1331451 for an explanation of why that is the case.
$myarray = explode(" ", $_GET['keywords']);
var_dump($myArray);
How's that?
Don't use plus symbol because The "+" sign you see is actually just an encoded space. use comma in URL while passing values from one page to another page here is solution after sending them in URL using comma separated form :-
$myArray = explode(',', $_REQUEST['keywords']);
after this you can get your data as following
$myArray[0]=this;
$myArray[1]=is;
$myArray[2]=an;
$myArray[3]=example;
$url = 'example/myproject.php?keywords=this+is+an+example';
$x = parse_url($url);
$y = str_replace("keywords=", "", $x["query"]);
var_dump(explode("+", $y));
First parse the url, second remove keywords=, next explode what's left by + sign.

Mysqli array failing?

I have a block of text and a preg_match_all sequence to create an array ($matches) from certain elements in the text.
I then look up a corresponding entry for each string in the first array using mysqli and receive a second array - ($replacement).
I want to replace the first array's position in the original text with the second array, re-finding the first array and naming it $arraytoreplace. This is the code I use:
$replacement = array();
$myq = "SELECT code,title FROM messages WHERE ID=?";
if ($stmt = $mysqli2->prepare($myq)) {
foreach($matches[1] as $value) {
$stmt->bind_param("s", $value);
$stmt->execute();
// bind result variables
$stmt->bind_result($d,$cc);
if($stmt->fetch()) {
$replacement[] = '' . $cc . '';
}
}
$stmt->close();
}
If I use var_dump on the arrays before the str_replace like so:
var_dump($arraytoreplace);
var_dump($replacement);
I get:
array(4) {
[0]=> string(3) "111"
[1]=> string(2) "12"
[2]=> string(4) "1234"
[3]=> string(1) "0"
}
array(4) {
[0]=> string(5) "hello"
[1]=> string(2) "hi"
[2]=> string(3) "foo"
[3]=> string(3) "bar"
}
I then use str_replace to drop the second array into the first array's place in the original text.
Usually this is fine, but everything breaks once it hits the 10 string in an array mark.
Instead of Text hello text hi I'll get Text 11foo text foo1 or something equally bizarre.
Any ideas?
Edit: The code used for replacing the arrays as follows:
$messageprep = str_replace($arraytoreplace, $replacement, $messagebody);
$messagepostprep = str_replace('#', '', $messageprep);
echo '<div class="messagebody">' . $messagepostprep . '</div>';
It looks like your getting partial replacements when a string of numbers is contained inside a longer string, i.e. 23 inside 1234.
You need to do your replacements with a regular expression on the boundary of the search string. Something like...
$text = preg_replace("/\b" . $replace . "\b/", $value, $text);
Another possible solution would be to consider changing the values to replace so that they are padded with zeros...
Array(
[0] => string(3) "0111"
[1] => string(2) "0012"
[2] => string(4) "1234"
[3] => string(1) "0000"
)
...and make sure that your search strings are also padded with zeros, because 0012 will never be confused with 12 and accidentally found in 0123.

Get particluar values from a string in PHP

My string is :
$mystring = "https://maps.google.com/?ll=37.0625,-95.677068&spn=37.188995,86.572266&t=m&z=4";
Now I want those values which I have marked as bold from the string. How can I achieve this with PHP?
Use the following functions parse_url and parse_str. You could do something like this the following
$url = "https://maps.google.com/?ll=**37.0625,-95.677068**&spn=**37.188995,86.572266**&t=m&z=4";
$parts = parse_url($url);
if(isset($parts['query'])) {
parse_str(urldecode($parts['query']), $result);
print_r($result)
}
use explode or parse_url or parse_str
you'll have to use $_GET['ll'] and $_GET['spn'] to repectively obtain 37.0625,-95.677068 and 37.188995,86.572266
Here regular expression will be most efficient to parse your required values.
$url = "https://maps.google.com/?ll=37.0625,-95.677068&spn=37.188995,86.572266&t=m&z=4";
$regex = "/[-]*\d+.\d*/";
preg_match_all($regex,$url,$out, PREG_PATTERN_ORDER);
// $out = array(1) { [0]=> array(4) { [0]=> string(7) "37.0625" [1]=> string(10) "-95.677068" [2]=> string(9) "37.188995" [3]=> string(9) "86.572266" } }

Categories