How to get a range of arrays - php

I have a code which I have to explode my text using "*" as a delimiter.
I have a pattern that always the array [0] and [1] will be excluded and the rest of them need to be included inside a variable, but my problem is that I don't know how to catch dynamically the rest of the arrays that I have to put them all together inside of it.
Specially because my text may have more "*" and explode into more parts, but I have to get them all together. Excluding the [0] and [1]
$item= explode("*",$c7);
print_r($item);
//so now that I know which are my [0] and [1] arrays I need to get the rest of them inside of another variable
$variable = ?? //the rest of the $item arrays

$str = 'a*b*c*d*e';
$newStr = implode('*', array_slice(explode('*', $str), 2)); // OUTPUT: c*d*e
explode() is used to chunk the string by a delimiter
implode() is used to build a string again from chunks
array_slice() is used to select a range of the elements

I realise an answer was already accepted, but explode has a third argument for this, and with end you can grab that last, non-split part:
$str = 'a*b*c*d*e';
$res = end(explode("*", $str, 3));
$res gets this value as a result:
c*d*e

I think based off of your question, if I interpreted it correctly something like below will be useful.
USING A LOOP
$str = "adssa*asdASD*AS*DA*SD*ASD*AS*DAS*D";
$parts = explode("*", $str);
$newStr = "";
for ($i = 2; $i < count($parts); ++$i) {
$newStr .= $parts[$i];
}

Related

How to remove any special character from php array?

How to remove any special character from php array?
I have array like:
$temp = array (".com",".in",".au",".cz");
I want result as:
$temp = array ("com","in","au","cz");
I got result by this way:
$temp = explode(",",str_replace(".","",implode(",",$temp)));
But is there any php array function with we can directly remove any character from all values of array? I tried and found only spaces can be removed with trim() but not for any character.
Use preg_replace function. This will replace anything that isn't a letter, number or space.
SEE DEMO
<?php
$temp = array (".com",".in",".aus",".cz");
$temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $temp );
print_r($temp);
//outputs
Array
(
[0] => com
[1] => in
[2] => aus
[3] => cz
)
?>
I generaly make a function
function make_slug($data)
{
$data_slug = trim($data," ");
$search = array('/','\\',':',';','!','#','#','$','%','^','*','(',')','_','+','=','|','{','}','[',']','"',"'",'<','>',',','?','~','`','&',' ','.');
$data_slug = str_replace($search, "", $data_slug);
return $data_slug;
}
And then call it in this way
$temp = array (".com",".in",".au",".cz");
for($i = 0; $i<count($temp); $i++)
{
$temp[$i] = make_slug($temp[$i]);
}
print_r($temp);
Each value of $temp will then become free of special characters
See the Demo
As a solution to your problem please execute the following code snippet
$temp = array (".com",".in",".au",".cz");
function strip_special_chars($v)
{
return str_replace('.','',$v);
}
$result[]=array_map('strip_special_chars',$temp);
Actually trim() can trim any character(s) you wish if you provide the 2nd argument (character mask). As it's name implies, this will only remove characters from the beginning and end of the string. In your case ltrim() may be more appropriate.
You can use array_map() and ltrim() together with a third parameter for the character mask like this:
$temp = array_map('ltrim', $temp, array_fill(0, count($temp), '.'));
The third parameter should be an array of arguments matching the length of the array you're processing, which is why I used array_fill() to create it.

adding link values around each string

I have a php value coming back from my database as a string, like
"this, that, another, another"
And I'm trying to wrap a separate link around each of those strings, but I can't seem to get it to work. I've tried a for loop, but since it's just a string of information and not an array of information that doesn't really work. Is there a way to wrap a unique link around each value in my string?
The easiest way that I see to do this would be using PHP's explode() function. You'll find that it will become very useful as you start to use PHP more and more, so do check out its documentation page. It allows you to split a string up into an array given a certain separator. In your case, this would be ,. So to split the string:
$string = 'this, that, another, another 2';
$parts = explode(', ', $string);
Then use a foreach (again, check the documentation) to iterate through each of the parts and make them into a link:
foreach($parts as $part) {
echo '' . $part . "\n";
}
However, you can do this with a for loop. Strings can be accessed like arrays, so you can implement a parser pattern to parse the string, extract the parts, and create the links.
// Initialize some vars that we'll need
$str = "this, that, another, another";
$output = ""; // final output
$buffer = ""; // buffer to hold current part
// Iterate over each character
for($i = 0; $i < strlen($str); $i++) {
// If the character is our separator
if($str[$i] === ',') {
// We've reached the end of this part, so add it to our output
$output .= '' . trim($buffer) . "\n";
// clear it so we can start storing the next part
$buffer = "";
// and skip to the next character
continue;
}
// Otherwise, add the character to the buffer for the current part
$buffer .= $str[$i];
}
echo $output;
(Codepad Demo)
A better way is to do it like this
$string = "this, that, another, another";
$ex_string = explode(",",$string);
foreach($ex_string AS $item)
{
echo "<a href='#'>".$item."</a><br />";
}
First explode the string to get the individual words in an array. Then add the hyperlinks to the words and finally implode them.
$string = "this, that, another, another";
$words = explode(",", $string);
$words[0] = $words[0]
$words[1] = $words[1]
..
$string = implode(",", $words);
You can also use the for loop to assign hyperlinks that follow a pattern like this:
for ($i=0; $i<count($words); $i++) {
//assign URL for each word as its name or index
}

Separate each word into a Array

I have a file with contents like :
Apple 100
banana 200
Cat 300
I want to search for a particular string in the file and get the next word. Eg: I search for cat, I get 300. I have looked up this solution: How to Find Next String After the Needle Using Strpos(), but that didn't help and I didn't get the expected output. I would be glad if you can suggest any method without using regex.
I'm not sure this is the best approach, but with the data you've provided, it'll work.
Get the contents of the file with fopen()
Separate the values into array elements with explode()
Iterate over your array and check each element's index as odd or even. Copy to new array.
Not perfect, but on the right track.
<?php
$filename = 'data.txt'; // Let's assume this is the file you mentioned
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
$clean = trim(preg_replace('/\s+/', ' ', $contents));
$flat_elems = explode(' ', $clean);
$ii = count($flat_elems);
for ($i = 0; $i < $ii; $i++) {
if ($i%2<1) $multi[$flat_elems[$i]] = $flat_elems[$i+1];
}
print_r($multi);
This outputs a multidimensional array like this:
Array
(
[Apple] => 100
[banana] => 200
[Cat] => 300
)
Try this, it doesn't use regex, but it will be inefficient if the string you're searching is longer:
function get_next_word($string, $preceding_word)
{
// Turns the string into an array by splitting on spaces
$words_as_array = explode(' ', $string);
// Search the array of words for the word before the word we want to return
if (($position = array_search($preceding_word, $words_as_array)) !== FALSE)
return $words_as_array[$position + 1]; // Returns the next word
else
return false; // Could not find word
}
$find = 'Apple';
preg_match_all('/' . $find . '\s(\d+)/', $content, $matches);
print_r($matches);
You might benefit from using named regex subpatterns to capture the information you're looking for.
For example you, finding a number the word that is its former (1 <= value <= 9999)
/*String to search*/
$str = "cat 300";
/*String to find*/
$find = "cat";
/*Search for value*/
preg_match("/^$find+\s*+(?P<value>[0-9]{1,4})$/", $str, $r);
/*Print results*/
print_r($r);
In cases where a match is found the results array will contain the number you're looking for indexed as 'value'.
This approach can be combined with
file_get_contents($file);

Prepend each line of a variable with a string

How can I prepend a string, say 'a' stored in the variable $x to each line of a multi-line string variable using PHP?
Can also use:
echo preg_replace('/^/m', $prefix, $string);
The / are delimiters. The ^ matches the beginning of a string. the m makes it multiline.
demo
There are many ways to achieve this.
One would be:
$multi_line_var = $x.str_replace("\n", "\n".$x, $multi_line_var);
Another would be:
$multi_line_var = explode("\n", $multi_line_var);
foreach($multi_line_var AS &$single_line_var) {
$single_line_var = $x.$single_line_var;
}
$multi_line_var = implode("\n", $multi_line_var);
Or as a deceitfully simple onliner:
$multi_line_var = $x.implode("\n".$x, explode("\n", $multi_line_var));
The second one is dreadfully wasteful compared to the first. It allocates memory for an array of strings. It runs over each array item and modifies it. And the glues the pieces back together.
But it can be useful if one concatenation is not the only alteration you're doing to those lines of text.
Because of your each line requirement, I would first split the string to an array using explode, then loop through the array and add text to the beginning of each line, and then turn the array back to a string using implode. As long as the number of lines is not very big, this can be a suitable solution.
Code sample:
$arr = explode("\n", $x);
foreach ($arr as $key => $value) {
$arr[$key] = 'a' . $arr[$key];
}
$x = implode("\n", $arr);
Example at: http://codepad.org/0WpJ41LE

String replace PHP

Array {
[0] => http://abc.com/video/ghgh23;
[1] => http://smtech.com/file/mwerq2;
}
I want to replace the content between /sometext/ from the above array. Like I want to replace video, file with abc.
You don't need to loop over every element of the array, str_replace can take an array to replace with:
$myArray = str_replace(array('/video/', '/file/'), '/abc/', $myArray);
However, based on your question, you might want to replace the first path segment, and not a specific index. So to do that:
$myArray = preg_replace('((?<!/)/([^/]+)/)', '/abc/', $myArray);
That will replace the first path element of every URL in $myArray with /abc/...
One way is to use str_replace()
You can check it out here: http://php.net/str_replace
Either str_replace as other comments suggested or using a regular expression especially if you might have a longer url with more segments like http://example.com/xxx/somestuff/morestuff
In that case str_replace will not be enough you will need preg_replace
This is another option. Supply a array, foreach will pick it up and then the first parameter of str_replace can be a array if needed. Hope you find this helpful.
<?php
$array = array('http://abc.com/video/ghgh23','http://smtech.com/file/mwerq2');
$newarray = array();
foreach($array as $url) {
$newarray[] = str_replace(array('video','file'),'abc',$url);
}
print_r($newarray);
?>
//every element in $myArray
for($i=0; $i < count($myArray); $i++){
$myArray[$i] = str_replace('/video/','/abc/',$myArray[$i]);
}
$array = array('http://abc.com/video/ghgh23', 'http://smtech.com/file/mwerq2');
foreach ($array as &$string)
{
$string = str_replace('video', 'abc', $string);
$string = str_replace('file', 'abc', $string);
}

Categories