remove part of string after 4th slash in php - php

I have an array which is contains links and trying to edit those links. Trying to cut links after 4th slash.
[0]=>
string(97) "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline"
[1]=>
string(105) "https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline"
[2]=>
string(91) "https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline"
expected output is like this:
[0]=>
string(97) "https://www.nowhere.com./downtoalley/"
[1]=>
string(105) "https://www.example.com./wowar-waseda/"
[2]=>
string(91) "https://www.hey.com./gotoashbourn/"
Lengths are different, so I can't use strtok any other options for this?

Try following code:
<?php
$arr = array(
0 => "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline",
1 => "https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline",
2 => "https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline");
$resultArray = array();
foreach($arr as $str) {
array_push($resultArray, current(explode("?",$str)));
}
print_r($resultArray);
?>
You can test this code here

You can use preg_replace to replace everything in each string after the fourth / with nothing using this regex
^(([^/]*/){4}).*$
which looks for 4 sets of non-/ characters followed by a /, collecting that text in capture group 1; and then replacing with $1 which gives only the text up to the 4th /:
$strings = array("https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline",
"https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline",
"https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline");
print_r(array_map(function ($v) { return preg_replace('#^(([^/]*/){4}).*$#', '$1', $v); }, $strings));
Output:
Array (
[0] => https://www.nowhere.com./downtoalley/
[1] => https://www.example.com./wowar-waseda/
[2] => https://www.hey.com./gotoashbourn/
)
Demo on 3v4l.org

There is no direct function to achieve this. You can follow PHP code as below:
$explodingLimit = 4;
$string = "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline";
$stringArray = explode ("/", $string);
$neededElements = array_slice($stringArray, 0, $explodingLimit);
echo implode("/", $neededElements);
I have made this for one element which you can use for you array. Also you can add last '/' if you need that. Hope it helps you.

Related

PHP Regex Pattern, removing span tags and inner text from string

I'm trying to format an array of strings, in order to strip out statements like this:
*<span class="exception">some text</span>
Many of these array items are just decimal numbers, but several instances contain html tags/text such as above. Here's some sample items from the array, to help put it into perspective:
'1.5',
'3.7',
'8.0',
'4.2*<span class="exception">some text</span>'
'5.7*<span class="exception">some text</span>random text to keep'
'4.9*<span class="exception">some text</span>8.0'
When I encounter items with '*some text', I need to remove the asterisk, the opening and closing span tags, and the text within the tags completely. The text within the tags is completely random. Additional text may follow the span tags, and in this case I would need to keep that text.
I've checked out several posts, including the following (the most helpful so far), but with only partial success: Regex to remove span tags using php
if (substr_count($value, '*<span') > 0) {
$value = preg_replace('/<span[^>]+\>/', '', $value);
}
This statement strips off the asterisk and the opening span tag, but not the closing span tag or the text between tags.
I'm fairly new to regex so any help or advice is certainly appreciated.
This should be it.. The [*] matches the * character while the .*> matches any up till the > character
if (substr_count($value, '*<span') > 0) {
$value = preg_replace('/[*].*>/', '', $value);
}
If everything follows this pattern, you don't need a regex just explode on the * and use the first element.
foreach( $array as $key => $value ){
$array[$key] = explode('*',$value)[0];
}
Result from your example:
array(4) {
[0]=>
string(3) "1.5"
[1]=>
string(3) "3.7"
[2]=>
string(3) "8.0"
[3]=>
string(3) "4.2"
}
EDIT
If there is "other stuff" after the tags it takes a little more work
$array = [
'1.5',
'3.7',
'8.0*<span class="exception">some text</span>',
'4.2*<span class="exception">some text</span>then other stuff'
];
foreach( $array as $key => $value ){
$sub = explode('*',$value);
$end = [];
if(count($sub) > 1) {
$end = explode('>',end($sub));
}
$array[$key] = trim($sub[0] . ' ' . end($end));
}
Result:
array(4) {
[0]=>
string(3) "1.5"
[1]=>
string(3) "3.7"
[2]=>
string(3) "8.0"
[3]=>
string(20) "4.2 then other stuff"
}
You can simply capture all components of unexpected HTMLs, then replace with anything that you wish, with a simple expression such as:
([0-9.]+)(.+?)<(.+?)>(.+?)<(\/.+?)>
Here, ([0-9.]+) captures the number in $1, followed by * in $2, (.+?), then open tag in $3, <(.+?)>, textConent in $4 (.+?) and closing tag in $5, <(\/.+?)>, and we can modify that, if we wish to capture anything else.
Test
$re = '/([0-9.]+)(.+?)<(.+?)>(.+?)<(\/.+?)>/m';
$str = '4.2*<span class="exception">some text</span>';
$subst = '$1';
$result = preg_replace($re, $subst, $str);
echo $result;
Demo
Do not parse HTML with regex. use a proper HTML parser instead, in your case
$arr = array(
'1.5',
'3.7',
'8.0',
'4.2*<span class="exception">some text</span>',
'5.7*<span class="exception">some text</span>random text to keep',
'4.9*<span class="exception">some text</span>8.0',
);
foreach ($arr as &$tmp) {
$domd = #DOMDocument::loadHTML('<?xml encoding="UTF-8"><main>' . $tmp . '</main>');
$main = $domd->getElementsByTagName("main")->item(0);
foreach ($main->getElementsByTagName("*") as $remove) {
$remove->parentNode->removeChild($remove);
}
$tmp = str_replace("*", " ", $main->textContent);
}
print_r($arr);
yields:
Array
(
[0] => 1.5
[1] => 3.7
[2] => 8.0
[3] => 4.2
[4] => 5.7 random text to keep
[5] => 4.9 8.0
)
$value = ['1.5',
'3.7',
'8.0',
'4.2*<span class="exception">some text</span>',
'5.7*<span class="exception">some text</span>random text to keep' ,
'4.9*<span class="exception">some text</span>8.0'];
foreach($value as $k=>$v){
$value[$k] = strip_tags($v);
}
print_r($value);

php5 copy sub-strings from string separated by space?

I am using php5 and have a script which will return IP addresses of the client.
Executing script using shell_exec() function. Now the output is like this: *192.168.10.40 192.168.10.41 *.
Now I need to store this in an array. I used preg_match() but it is not working.
Here is the code using preg_match() :
$test = shell_exec("/www/dhcp.sh");
$pattern='/([^ ]*) /';
preg_match($pattern, $test, $new);
preg_match() is returning 0;
Here is the one I used explode() :
$test = shell_exec("/www/dhcp.sh");
var_dump( explode(' ', $test ) );
I also used explode but I am getting the result as:
array(1) { [0]=> string(28) "192.168.10.40 192.168.10.41 " }
Can anyone tell me how can I split the string into an array?
Regards,
Sowmya
You can use explode to split your string:
explode(' ', '192.168.10.40 192.168.10.41'));
which gives you
array(2) {
[0]=>
string(13) "192.168.10.40"
[1]=>
string(13) "192.168.10.41"
}
http://php.net/manual/fr/function.explode.php

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"
}

how can split the result set array to string in php

i need help. i was developed a page in smarty , i got a result set from a query and i need to change the result set to string and stored in text area
my query is given below
select val from test
my result set is print in var_dump in controller
{ [0]=> array(1) { ["val"]=> string(1) "c" } [1]=> array(1) { ["val"]=> string(3) "c++" } [2]=> array(1) { ["val"]=> string(4) "java" } [3]=> array(1) { ["val"]=> string(3) "PHP" } }
i need to change in to sting like c,c++,java,PHP
the changing function is preformed only controller
ple help me.. and thk adv
Use foreach for that. See more information here - http://php.net/manual/en/control-structures.foreach.php .
Example -
$array = Array("333", "222", "111");
foreach($array as $string) {
echo $string.'<br />';
}
Another solution would be to use implode.
See more information here - http://php.net/manual/en/function.implode.php and again a small example -
$array = Array("333", "222", "111");
$strings = implode(",", $array); // comma in first quotes are seperator, you can set it also to " " for a single space.
echo $strings; // In this case it will output 333,222,111 if you would set it to empty space then it would output 333 222 11
EDIT:
For writing in file you must use file functions.
Check this link - http://php.net/manual/en/function.file-put-contents.php
example -
// your file
$file = 'sample.txt';
$array = Array("333", "222", "111");
// Add all strings to $content.
foreach($array as $string) {
$content .= $string.'<br />';
}
// write everything in file
file_put_contents($file, $content);
Suggestion:
When you are writing SQL queries, I would suggest that you already now start learning to write them correctly, so they are easier to read.
For example, your query -
select val from test
Could be changed to -
SELECT `val` FROM `test`
which is alot easier to read and understand.
If You need to join all array with some delimeters, then use implode.
Example:
$arr = array("hi", "peter!", "how", "are", "you");
echo implode(" ", $arr) . "?";
//output
// hi peter! how are you?
If you want a string separated by commas, you must use the implode function
string implode ( string $glue , array $pieces )
glue: Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.
pieces:The array of strings to implode.
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
http://www.php.net/manual/en/function.implode.php
Example
$array = Array("333", "222", "111");
$string = explode(',', $array);
returns
"333,222,111"
if you want spaces:
$string = explode(' ', $array);
returns
"333 222 111"

Why preg_match fails to get the result?

I have the below text displayed on the browser and trying to get the URL from the string.
string 1 = voice-to-text from #switzerland: http://bit.ly/lnpDC12D
When I try to use preg_match and trying to get the URL, but it fails
$urlstr = "";
preg_match('/\b((?#protocol)https?|ftp):\/\/((?#domain)[-A-Z0-9.]+)((?#file)\/[-A-Z0-9+&##\/%=~_|!:,.;]*)?((?#parameters)\?[A-Z0-9+&##\/%
=~_|!:,.;]*)?/i', $urlstr, $match);
echo $match[0];
I think #switzerland: has one more http// ... will it be problem ?
the above split works perfect for the below string,
voice-to-text: http://bit.ly/jDcXrZg
In this case I think parse_url will be better choice than regex based code. Something like this may work (assuming your URL always starts with http):
$str = "voice-to-text from #switzerland: http://bit.ly/lnpDC12D";
$pos = strrpos($str, "http://");
if ($pos>=0) {
var_dump(parse_url(substr($str, $pos)));
}
OUTPUT
array(3) {
["scheme"]=>
string(4) "http"
["host"]=>
string(6) "bit.ly"
["path"]=>
string(9) "/lnpDC12D"
}
As far as I understand your request, here is a way to do it :
$str = 'voice-to-text from <a href="search.twitter.com/…;: http://bit.ly/lnpDC12D';
preg_match("~(bit.ly/\S+)~", $str, $m);
print_r($m);
output:
Array
(
[0] => bit.ly/lnpDC12D
[1] => bit.ly/lnpDC12D
)

Categories