I've always had problems with strpos, I understand the num v. boolean issue, but I can NOT get this working. The $cur_key value is something like "page=>name"...
$pos = strpos($cur_key, "=>");
if ($pos !== false) {
$mod = explode("=>",$cur_key);
$path = $mod[0];
$param = $mod[1];
}else{
$path = $cur_key;
}
If it's in there it should split it into the two values but no matter what I try it's always just returning the original value...
$mod = explode('=>',$cur_key);
$path=$mod[0];
if (sizeof($mod)>1) $param=$mod[1]; else $param='';
Related
I have a function to clean a link when I filter my search results
function cleanLink($url,$remove){
$aQ = explode("&",str_replace("?", "", $url));
foreach ($aQ as $part) {
$pos = strpos($part, $remove);
if ($pos === false)
$queryClean[] = $part;
}
$line = implode("&", $queryClean);
return "?".$line;
}
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
This works fine, for example if my url is
www.mysite.com/?q=wordx
I want to add an "order alphabetic desc" so my url returns
www.mysite.com/?q=wordx&order=desc
but if my query string is empty (e.g. www.mysite.com/) the return is
www.mysite.com/?&q=word
How can I remove the & if the query string is empty?
Change
if ($pos === false)
to
if ($pos === false && $part)
to omit empty $part string (will evaluate as false). You also should initialize $queryClean
$queryClean = array();
You can use parse_str and http_build_str to remove a parameter from the query string. You just to make sure pecl_http >= 0.23.0 is installed
function cleanLink($queryString, $remove)
{
parse_str($queryString, $query);
if (array_key_exists($remove, $query)) {
unset($query[$remove]);
}
return http_build_str($query);
}
$linkACTUAL = $_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q");
echo $linkACTUAL . "&q=" . $word;
For more information see http://php.net/manual/en/function.http-build-str.php and http://php.net/manual/de/function.parse-str.php
If your function is running fine when there are query string then you can simply put your function call inside if statement like
if(!empty($_GET))
{
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
}
Updated:
echo (false === strpos($linkACTUAL, "&")) ? $linkACTUAL."q=".$word : $linkACTUAL."&q=".$word;
Before I got this answer
preg_replace("~(?<=$str&&).*~", '7', $str);
which is good but what if within the array I have a similar string mary&&5 and rosemary&&5 and I stricktly want to change only mary&&5 and not disturb the other array, is it posible? and how?
The question before was:
`$array = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8", etc..);`
and I know only the string before && which is username. $str = "mary&&"; Note that I don't know what is after &&
I want to know whether exist or not within the array, and if exist change the value to something new like mary&&7
`$isExists = preg_replace("some","some", $array);
if ($isExists){
echo "Its exists";
} else {
echo "Not exixts"
} ;`
How can I change the portion of the value after && in mary&&5 or completely change mary&&5 to mary&&7 since I don't know before hand the value mary&&5?
Thanks for your answer :)
`$name = "mary";
$res = "7";
$str = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8","rosemary&&5");
for ($i = 0; $i < count($str); ++$i) {
$r = preg_replace("~(?<=$name).*~",$res, $str);}`
$arr = array('josh&&3', 'mary&&5', 'cape&&4', 'doggy&&8', 'rosemary&&5');
$name = 'mary';
$number = '7';
$replacement = $name . '&&' . $number;
So, a way without regex:
foreach($arr as $k=>$v) {
if (explode('&&', $v)[0] === $name)
$arr[$k] = $replacement;
}
( or you can use strpos($v, $name . '&&') === 0 as condition)
a way with regex:
$arr = preg_filter('~\A' . $name . '&&\K.*~', $number, $arr);
(where \K removes all on the left from the match result, so the name and && aren't replaced)
I have some image collection in my specied directory.And i want to get their name using readdir() function.But instead of showing their names,it prints out a series of 1.How this can be done correctly ??I also want to know the reason for this behaviour
$dir='c:/xampp/htdocs/practice/haha/';
echo getcwd().'</br>';
if(is_dir($dir)){
echo dirname($dir);
$file=opendir($dir);
while($data=readdir($file)!==false){
echo $data.'</br>';
}
}
Operator precedence. This line:
while($data=readdir($file)!==false){
is being parsed/executed as
while ($data = (readdir($file) !== false))
^------------------------^
Note the extra brackets. $data is getting the boolean TRUE result of the !== comparison. You need to rewerite as
while(($data = readdir($file)) !== false){
^----------------------^
That'll make $data get the string returned from readdir, and then that string will be compared with boolean false.
Relevant docs: http://php.net/manual/en/language.operators.precedence.php
You probably can implement instead with scandir
function list_directory($directory) {
$result = new stdClass();
$result->path = $directory;
$result->children = array();
$dir = scandir($directory);
foreach($dir as $file) {
if($file == '.' || $file == '..') continue;
$result->children[] =
!is_dir($directory.$file) ? $file :
list_directory($directory.$file.'/');
}
return $result;
}
$dir='c:/xampp/htdocs/practice/haha/';
$result = list_directory($dir);
echo '<code><pre>';
var_dump($result);
echo '</pre></code>';
You can add in the function a filter for filetypes, or limit depth of recursion, things like that.
$data=readdir($file)!==false
You're setting the boolean result to $data. Surely you meant to do:
($data=readdir($file))!==false
I have this code:
$getClass = $params->get('pageclass_sfx');
var_dump($getClass); die();
The code above returns this:
string(24) "sl-articulo sl-categoria"
How can I retrieve the specific word I want without mattering its position?
Ive seen people use arrays for this but that would depend on the position (I think) that you enter these strings and these positions may vary.
For example:
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
echo $arr[0];
$arr[0] would return: sl-articulo
$arr[1] would return: sl-categoria
Thanks.
You can use substr for that in combination with strpos:
http://nl1.php.net/substr
http://nl1.php.net/strpos
$word = 'sl-categoria';
$page_class_sfx = $params->get('page_class_sfx');
if (false !== ($pos = strpos($page_class_sfx, $word))) {
// stupid because you already have the word... But this is what you request if I understand correctly
echo 'found: ' . substr($page_class_sfx, $pos, strlen($word));
}
Not sure if you want to get a word from the string if you already know the word... You want to know if it's there? false !== strpos($page_class_sfx, $word) would be enough.
If you know exactly what strings you're looking for, then stripos() should be sufficient (or strpos() if you need case-sensitivity). For example:
$myvalue = $params->get('pageclass_sfx');
$pos = stripos($myvalue, "sl-articulo");
if ($pos === FALSE) {
// string "sl-articulo" was not found
} else {
// string "sl-articulo" was found at character position $pos
}
If you need to check if some word are in string you may use preg_match function.
if (preg_match('/some-word/', 'many some-words')) {
echo 'some-word';
}
But this solution can be used for a small list of needed words.
For other cases i suggest you to use some of this.
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
$result = array();
foreach($arr as $key=> $value) {
// This will calculates all data in string.
if (!isset($result[$value])) {
$result[$value] = array(); // or 0 if you don`t need to use positions
}
$result[$value][] = $key; // For all positions
// $result[$value] ++; // For count of this word in string
}
// You can just test some words like follow:
if (isset($result['sl-categoria'])) {
var_dump($result['sl-categoria']);
}
I have urls such as
/blah/WHATEVER/sites/two/one/blah/need/this.ini
in PHP, how do I extract /need/this.ini with regular expressions?
Without:
$url = '/blah/WHATEVER/sites/two/one/blah/need/this.ini';
$array = explode('/',$url);
$rev = array_reverse($array);
$last = $rev[0];
$second_last = $rev[1];
// or $rev[1].'/'.$rev[0]
A bit longer, I'm sure there are even better and clearer ways than this. Anyway, just to say you don't need regexes for this kind of stuff. Regexes are not a solution for everything :)
If you don't need the array intact, you can also array_pop() twice, and each time you get the last element. But you will shorten the array by one element each time.
Also:
$url = '/blah/WHATEVER/sites/two/one/blah/need/this.ini';
$array = explode('/',$url);
$last = end($array);
$second_last = prev($array);
See it in action
This should do:
(/[^/]+/[^/]+)$
(does not check for escaped slashes though.)
Notice # instead of /
if (preg_match('#/?[^/]+?/?[^/]+$#', $path, $m) !== false) {
// $m[0]` will contain the desired part
}
But there is better way to do this - don't use regexp at all:
function extract_part($path) {
$pos = strrpos( $path, '/');
if ($pos > 0) { // try to find the second one
$npath = substr($path, 0, $pos-1);
$npos = strrpos($npath, '/');
if ($npos !== false) {
return substr($path, $npos);
}
// This is not error, uncomment to change code behaviour.
/*else { // Returns '/this.ini' in your case
return substr($path, $pos);
}*/
}
// Returns as is
return $path;
}
(I have no php interpreter under my hands, so the code is not checked).
Yep, there was an error :) and now its fixed.