PHP file_exists and wildcard - php

Is there a way to write the PHP file_exists function so that it searches a directory for a file with an arbitrary extension. For instance, suppose I knew that a file were called "hello", but I didn't know the extension, how would I write a function that searched for a file called hello.* and returned the name of this file? As far as I can tell, file_exists will only search for a string.
Thanks.

You're looking for the glob() function.
file_exists doesn't do any kind of search : it only allows one to know whether a file exists or not, when knowing its name.
And, with PHP >= 5.3, you could use the new GlobIterator.
As an example with `glob()`, the following portion of code :
$list = glob('temp*.php');
var_dump($list);
Gives me this output :
array
0 => string 'temp-2.php' (length=10)
1 => string 'temp.php' (length=8)
While this one :
$list = glob('te*-*');
var_dump($list);
Yes, with two * ;-)
Will give me :
array
0 => string 'temp-2.php' (length=10)
1 => string 'test-1.php' (length=10)
2 => string 'test-curl.php' (length=13)
3 => string 'test-phing-1' (length=12)
4 => string 'test-phpdoc' (length=11)

As of PHP5.3, you can also use the GlobIterator to search a directory with wildcards:
$it = iterator_to_array(
new GlobIterator('/some/path/*.pdf', GlobIterator::CURRENT_AS_PATHNAME) );
would return the full paths to all .pdf files in some/path in an array. The above performs about the same as glob(), but iterators provide a more powerful and extensible API.

As long as file_exists returns a BOOLEAN I wrote this small function
that accepts a search string with * to look for files...
Example:
searchForFile("temp*");
function searchForFile($fileToSearchFor){
$numberOfFiles = count(glob($fileToSearchFor));
return ($numberOfFiles > 0);
}

If you need a little more control and are on pre PHP 5.3 you could use a DirectoryIterator or RecursiveDirectoryIterator. Both have a lot of great function for added control and manipulation.
PHP docs are at DirectoryIterator and RecursiveDirectoryIterator

You can use fnmatch to match one filename against a pattern. Use this in a loop over all files.
if (fnmatch("hello*", $filename)) {
echo 'true';
}

Related

evaluate string with array php

I have a string like
"subscription link :%list:subscription%
unsubscription link :%list:unsubscription%
------- etc"
AND
I have an array like
$variables['list']['subscription']='example.com/sub';
$variables['list']['unsubscription']='example.com/unsub';
----------etc.
I need to replace %list:subscription% with $variables['list']['subscription'],And so on
here list is first index and subscription is the second index from $variable
.Is possible to use eval() for this? I don't have any idea to do this,please help me
Str replace should work for most cases:
foreach($variables as $key_l1 => $value_l1)
foreach($value_l1 as $key_l2 => $value_l2)
$string = str_replace('%'.$key_l1.':'.$key_l2.'%', $value_l2, $string);
Eval forks a new PHP process which is resource intensive -- so unless you've got some serious work cut out for eval it's going to slow you down.
Besides the speed issue, evals can also be exploited if the origin of the code comes from the public users.
You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.
Then you include the php file in your current module and call the function which will return the array.
I would use regular expression and do it like that:
$stringWithLinks = "";
$variables = array();
// your link pattern, in this case
// the i in the end makes it case insensitive
$pattern = '/%([a-z]+):([a-z]+)%/i';
$matches = array();
// http://cz2.php.net/manual/en/function.preg-replace-callback.php
$stringWithReplacedMarkers = preg_replace_callback(
$pattern,
function($mathces) {
// important fact: $matches[0] contains the whole matched string
return $variables[$mathces[1]][$mathces[2]];
},
$stringWithLinks);
You can obviously write the pattern right inside, I simply want to make it clearer. Check PHP manual for more regular expression possibilities. The method I used is here:
http://cz2.php.net/manual/en/function.preg-replace-callback.php

How to recognize translatable strings by xgettext in PHP Arrays or DocBlocks (without method calls)?

I'm using poEdit with the xgettext-Parser to parse my PHP source files and detect all translatable strings. By default, xgettext only recognizes strings in function calls like translate("foo"),
if "translate" is specified as a keyword for xgettext.
Now I have some translatable strings in PHP-arrays, like
array(
'label' => 'foo',
);
or DocBlocks like
/**
* #FormElement(type="text", options={
* "label"="Foobar",
* })
*/
How can I manage to recognize these translatable strings "foo" or "Foobar" with xgettext?
Thanks in advance!
You could create a dummy translate method, and use that when you create your array:
function dummy_translate ($string)
{
return $string;
}
$array = array
(
'label' => dummy_translate('foo')
);
And extract with:
xgettext --keyword=dummy_translate:1
Also as your xgettext keywords must form a valid C identifier, you cannot do this, just before the array:
$dummy_method = function ($string)
{
return $string;
}
Just find a good place to put your dummy method.
Did not use DocBlocks for more than documentations, so not sure about that, but I guess a similar approach should work there to.
P.S. The performance of the extra function call is negligible, please don't waste time with micro-optimizations.

Zend Framework Mysql WHERE IN clause

Using the zend framework i have used a query,having a IN clause,this is my query
$select->where('p.brandid IN (?)',$details[brand]);
in the above query, $details[brand] has a value like this array(1,2,3) .
Actually the query has to return all the values which are all related to this array(1,2,3).
But my query is returning the result related to the first value present in the above array(1,2,3).ie 1 alone other 2,3 is not considered.
when i print this query it shows like this
[where] => Array
(
[0] => (p.brandid IN ('1,2,3'))
)
Can anyone show me what is the mistake i have made or solution for this..
This is because your query is getting formed wrongly p.brandid IN ('1,2,3') instead of p.brandid IN (1,2,3) you can try using implode function in php
$select->where('p.brandid IN (?)',implode(",",$details[brand]));
Just small research, because I have the same problem.
I am not sure what version of Zend do you use. But solution provided by #Omesh doesn't work with my version 1.12.
In my case it is absolutely opposite explode solution:
$select->where('p.brandid IN (?)', explode(',',$details[brand]));
Probably it depends on the type of $details['brand']. In my case I have string like 555,666,777,877. But even if you have array there. That is strange if Zend accept in your case string (result of implode) and does not accept array. And in my case it does not accept string but accept array.
You can modify this according to Zend framwork
locate(concat(',',$details[brand],','),concat(',',p.brandid,','))>0
Just use
$select->where->in('field_name', $your_simple_array);
If you using where() function with something criteria before, like
$select->where(['field_name' => $value]);
just use the first one after it, like
$select->where(['field_name' => $value]);
$select->where->in('field_name', $your_simple_array);
Always remember to use where not as a function where(), but just as a keyword.
This is valid and tested by me in the following context:
$select = $this->tableGateway->getSql()->select()->where(['field1' => $v1, 'field2' => $v2]);
$select->where->in('field_name', ['v1', 'v2', 'v3']);
That is, using these libraries in the beginning of the model class:
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

PHP String Split

I need to split a string into chunks of 2,2,3,3 characters and was able to do so in Perl by using unpack:
unpack("A2A2A3A3", 'thisisloremipsum');
However the same function does not work in PHP, it gives this output:
Array
(
[A2A3A3] => th
)
How can I do this by using unpack? I don't want to write a function for it, it should be possible with unpack but how?
Thanks in advance,
Quoting the manual page of unpack :
unpack() works slightly different
from Perl as the unpacked data is
stored in an associative array.
To accomplish this you have to
name the different format codes and separate them by a slash /.
Which means that, using something like this :
$a = unpack("A2first/A2second/A3third/A3fourth", 'thisisloremipsum');
var_dump($a);
You'll get the following output :
array
'first' => string 'th' (length=2)
'second' => string 'is' (length=2)
'third' => string 'isl' (length=3)
'fourth' => string 'ore' (length=3)
I've never used this function, but according to the documentation, the A character means "SPACE-padded string". So I'd hazard a guess that it's only taking the first two characters of the first word.
Have you tried unpack("A2A2A3A3", 'this is lorem ipsum'); ?

Don't understand serialize()

I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?
Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can unserialize that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Ability to transmit (almost) any kind of PHP data from one PHP script to another
Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...
In the PHP manual, you can also read the Object Serialization section, btw.
If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.
json_encode() and json_decode() are similar except they encode as JSON.
See this example, should be pretty clear.

Categories