explode string one by one character including space [duplicate] - php

This question already has answers here:
php explode all characters [duplicate]
(4 answers)
Closed 8 years ago.
how i can explode string into an array. Acctually i want to translate english language into the braille. First thing i need to do is to get the character one by one from a string,then convert them by mathing the char from value in database and display the braille code using the pic. As example when user enter "abc ef", this will create value separately between each other.
Array
(
[0] => a
[1] => b
[2] => c
[3] =>
[4] => e
[5] => f
)
i tried to do but not get the desired output. This code separated entire string.
$papar = preg_split('/[\s]+/', $data);
print_r($papar);
I'm sorry for simple question,and if you all have an idea how i should do to translate it, feel free to help. :)

If you're using PHP5, str_split will do precisely what you're seeking to accomplish. It splits each character in a string – including spaces – into an individual element, then returns an array of those elements:
$array = str_split("abc ef");
print_r($array);
Outputs the following:
Array
(
[0] => a
[1] => b
[2] => c
[3] =>
[4] => e
[5] => f
)
UPDATE:
The PHP4 solution is to use preg_split. Pass a double forward slash as the matching pattern to delimit the split character-by-character. Then, set the PREG_SPLIT_NO_EMPTY flag to ensure that no empty pieces will be returned at the start and end of the string:
$array = preg_split('//', "abc ef", -1, PREG_SPLIT_NO_EMPTY); // Returns same array as above

PHP has a very simple method of getting the character at a specific index.
To do this, utilize the substring method and pass in the index you are looking for.
How I would approach your problem is
Ensure the string you are converting has at least a size of one
Determine how long the string is
int strlen ( string $string )
Loop over each character and do some operation depending on that character
With a string "abcdef"
$rest = substr("abcdef", -1); // returns "f"
See the substr page for a full example and more information
http://us2.php.net/substr

You can iterate the string itself.
$data = 'something string';
for($ctr = 0; $ctr < strlen($data); $ctr++)
{
if($data{$ctr}):
$kk = mysql_query("select braille_teks from braille where id_huruf = '$data{$ctr}'");
$jj = mysql_fetch_array($kk);
$gambar = $jj['braille_teks'];
?>
<img src="images/<?php echo $gambar;?>">
<?php
else:
echo "&nbsp";
}

Related

Explode a string where the explode condition is bunch of specific characters

I'm looking for a way to explode a string. For example, I have the following string: (we don't count the beginning - 0x)
0xa9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368
which is actually an ETH transaction input. I need to explode this string into 3 parts. Imagine 1 bunch of zeros is actually a single space and these spaces define the gates where the string should be exploded.
How can I do that?
preg_split()
This function uses a regular expression to split a string.
So in this example at two or more 0 in a row:
$arr = preg_split('/[0]{2,}/', $string);
print_r($arr);
echo PHP_EOL;
This will output the following:
Array
(
[0] => a9059xbb
[1] => fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d
[2] => 54368
)
Be aware that you will have problems if a message itself has a 00 in it. Assuming it is used as a null-byte for "end of string", this will not happen, though.
preg_match()
This is an example using regular expressions. You can split at arbitrary points.
$string = 'a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368';
print_r($string);
echo PHP_EOL;
$res = preg_match('/(.{4})(.{32})(.{32})/', $string, $matches);
print_r($matches);
echo PHP_EOL;
This outputs:
a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368
Array
(
[0] => a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199a
[1] => a905
[2] => 9xbb000000000000000000000000fc7a
[3] => 5f48a1a1b3f48e7dcb1f23a1ea24199a
)
As you can see /(.{4})(.{32})(.{32})/ will find 4 bytes, then 32 and after that 32 again. Capturing groups are made with () around what you want to find. They appear in the $matches array (0 is always the whole string found).
In case you want to ignore certain parts you can express that as well:
/(.{4})9x(.{32}).{4}(.{32})/
This changes the found string:
Array
(
[0] => a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d000
[1] => a905
[2] => bb000000000000000000000000fc7a5f
[3] => a1b3f48e7dcb1f23a1ea24199af4d000
)
Links
PHP documentation for the mentioned functions:
https://www.php.net/manual/en/function.preg-split.php
https://www.php.net/manual/en/book.pcre.php
Play around with the second regular expression using this demo:
https://regex101.com/r/pfZtH8/1
If you will always explode them at the same points (4 bytes(8 hexadecimal digits), 32 bytes(64 hexadecimal digits), 32 bytes(64 hexadecimal digits)), you could use substr().
$input = "0xa9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368";
$first = substr($input,2,8);
$second = substr($input,10,64);
$third = substr($input,74,64);
print_r($first);
print "<br>";
print_r($second);
print "<br>";
print_r($third);
print "<br>";
this outputs:
a9059xbb
000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d0
0000000000000000000000000000000000000000000000000000000000054368

How to split string with special character (�) using PHP

Currently I am trying to split the � the special character which represents %A0 at the URL. However when I use another URL, it doesn't recognize %A0 therefore I need to use %20 which is the standard space.
My question is. Is there a way to explode() special character �? Whenever I try to explode, it always return a single index array with length 1 array.
//Tried str_replace() to replace %A0 to empty string. Didn't work
$a = str_replace("%A0"," ", $_GET['view']);
// Tried to explode() but still returning single element
$b = explode("�", $a);
// Returning Array[0] => "Hello World" insteand of
// Array[2] => [0] => "Hello", [1] => "World"
echo $b[0];
Take a look at mb_split:
array mb_split ( string $pattern , string $string [, int $limit = -1 ] )
Split a multibyte string using regular expression pattern and returns
the result as an array.
Like this:
$string = "a�b�k�e";
$chunks = mb_split("�", $string);
print_r($chunks);
Outputs:
Array
(
[0] => a
[1] => b
[2] => k
[3] => e
)

How to get an array in a string in php?

If I have a string like this ,
$my_string="array('red','blue')";
How can I convert this to a real array ?
Example. :
$my_array=array('red','blue');
DO NOT USE EVAL. That is terrible overkill and very probably extremely unsafe.
While this is not the BEST way of doing this (as mentioned in question comments), you can use this below function to do exactly what you need.
How it works:
It uses Regex to find and split the string based on these layouts, the array is split using preg_split which is a regex verson of the more popular explode.
Once split the array will have some blank values so simply use array_filter to remove these blank values.
so:
// Explode string based on regex detection of:
//
// (^\h*[a-z]*\h*\(\h*')
// 1) a-z text with spaces around it and then an opening bracket
// ^ denotes the start of the string
// | denotes a regex OR operator.
// \h denotes whitespace, * denotes zero or more times.
//
// ('\h*,\h*')
// 2) or on '),(' with possible spaces around it
//
// ('\h*\)\h*$)
// 3) or on the final trailing '), again with possible spaces.
// $ denotes the end of the string
// the /i denotes case insensitive.
function makeArray($string){
$stringParts = preg_split("/(^\h*[a-z]*\h*\(\h*')|('\h*,\h*')|('\h*\)\h*$)/i",$string);
// now remove empty array values.
$stringParts = array_filter($stringParts);
return $stringParts;
}
Usage:
//input
$myString = " array('red','blue')";
//action
$array = makeArray($myString);
//output
print_r($array);
Output:
Array (
[1] => red
[2] => blue
)
Example 2:
$myString = " array('red','blue','horses', 'crabs (apples)', '(trapdoor)', '<strong>works</strong>', '436')";
$array = makeArray($myString);
print_r($array);
Output:
Array (
[1] => red
[2] => blue
[3] => horses
[4] => crabs (apples)
[5] => (trapdoor)
[6] => <strong>works</strong>
[7] => 436
)
Obviously the regex may need slight tweaking based on your exact circumstances but this is a very good starting point...
Reference Question/Answers

Split magnet link with PHP [duplicate]

This question already has answers here:
Magnet links library for PHP
(3 answers)
Closed 8 years ago.
I need two items in a magnet link:
magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337
the value of btih:
0eb69459a28b08400c5f05bad3e63235b9853021
and the value of the first udp:
udp://tracker.com:80
How to do this with PHP?
As parse_url() wont help in this situation your have to use regex to parse the string, and then further manipulate the string to get the trackers. So something like:
<?php
$string = 'magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337';
preg_match('#magnet:\?xt=urn:btih:(?<hash>.*?)&dn=(?<filename>.*?)&tr=(?<trackers>.*?)$#', $string, $magnet_link);
//0eb69459a28b08400c5f05bad3e63235b9853021
echo $magnet_link['hash'];
//Splinter.Cell.Blacklist-RELOADED
echo $magnet_link['filename'];
/*[trackers] => Array
(
[0] => udp://tracker.com:80
[1] => udp://tracker.publicbt.com:80
[2] => udp://tracker.istole.it:6969
[3] => udp://tracker.ccc.de:80
[4] => udp://open.demonii.com:1337
)
*/
$magnet_link['trackers'] = explode('&', urldecode(str_replace('tr=','', $magnet_link['trackers'])));
//so to get first tracker
$magnet_link['trackers'][0];
?>
As recommended in the question comments, there appear to be several existing libraries for magnet links - you should probably take a look at these.
If you want to do it yourself however, one way would be to regex for the values. Let's assume that your magnet link is assigned to a variable $link like so:
$link ='magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337';
A quick way to get each value is to run a separate preg_match() for each value - you could combine the two regexes and run preg_match_all() but let's keep it basic. We're going to use lookbehind assertions to try and find the required values.
// your magnet link
$link = 'magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337';
// urls are encoded, let's reverse that
$link = urldecode($link);
// first regex searches for 'btih:' and matches subsequent
// word characters ([a-zA-Z0-9_])
// match(es) are captured as an array to $matchBtih
preg_match('/(?<=btih:)\w+/', $link, $matchBtih);
// same again, more or less, capturing word characters, colon and full-stop
// match(es) are captured as an array to $matchUdp
preg_match('/(?<=tr=)udp:\/\/[\w\:\.]+/', $link, $matchUdp);
// show results
var_dump($matchBtih, $matchUdp);
Should yield:
array (size=1)
0 => string '0eb69459a28b08400c5f05bad3e63235b9853021' (length=40)
array (size=1)
0 => string 'udp://tracker.com:80' (length=20)
Hope this helps :)

trying to filter string with <br> tags using explode, does not work

I get a string that looks like this
<br>
ACCEPT:YES
<br>
SMMD:tv240245ce
<br>
is contained in a variable $_session['result']
I am trying to parse through this string and get the following either in an array or as separate variables
ACCEPT:YES
tv240245ce
I first tried
to explode the string using as the delimiter, and that did not work
then I already tried
$yes = explode(":", strip_tags($_SESSION['result']));
echo print_r($yes);
which gives me an array like so
Array ( [0] => ACCEPT [1] => YESSEED [2] => tv240245ce ) 1
which gives me one of my answers.
Please what would be a great way of trying to achieve what I am trying to achieve?
is there a way to get rid of the first and last?
then use the remaining one as a delimiter to explode the string ?
or what's the best way to go about this ?
This will do it:
$data=preg_split('/\s?<br>\s?/', str_replace('SMMD:','',$data), NULL, PREG_SPLIT_NO_EMPTY);
See example here:
CodePad
You can also skip caring about the spurious <br> and treat the whole string as key:value format with a simple regex like:
preg_match_all('/^(\w+):(.*)/', $text, $result, PREG_SET_ORDER);
This requires that you really have line breaks in it though. Gives you a $result list which is easy to convert into an associative array afterwards:
[0] => Array
(
[0] => ACCEPT:YES
[1] => ACCEPT
[2] => YES
)
[1] => Array
(
[0] => SMMD:tv240245ce
[1] => SMMD
[2] => tv240245ce
)
First, do a str_replace to remove all instances of "SMMD:". Then, Explode on "< b r >\n". Sorry for weird spaced, it was encoding the line break.
Include the new line character and you should get the array you want:
$mystr = str_replace( 'SMMD:', '', $mystr );
$res_array = explode( "<br>\n", $mystr );

Categories