Click to See Complete Forum and Search --> : Counting in a string
firman
08-02-2007, 01:18 PM
Say I have
$file = me/you/this/that/open.php
How can I count how many / are in a string?
Or better yet... how can I replace the words in between the / with ..
?
ellisgl
08-02-2007, 01:26 PM
Opps
firman
08-02-2007, 01:27 PM
That will only give me the position of the / not how many there are
ellisgl
08-02-2007, 01:30 PM
Opps - thinking here try this:
<?php
$text = split('/',$file);
$count = count($text);
echo $count;
?>
ellisgl
08-02-2007, 01:33 PM
As for the replacement use http://www.php.net/preg_replace - I'm not good with regexp..
sitehatchery
08-02-2007, 02:11 PM
//1st question
$file = 'me/you/this/that/open.php';
$arr=explode('/', $file);
$count=count($arr)-1;
echo $count;
echo "<br>";
//2nd question
$val=array('what', 'is', 'your', 'last', 'name.php');
echo implode('/', $val);
firman
08-02-2007, 02:43 PM
How about to replace the words in the file?
ellisgl
08-02-2007, 02:59 PM
if you have your stuff in an array - you could search the array for what you want if it has to be dynamic - get the key - update that key - combine and there you go.
if you know the key then you could just do $arr[5] = 'monkey';
sitehatchery
08-02-2007, 03:19 PM
ok, in the file itself.
$base='/me/you/this/that/';
$old='open.php';
$new='closed.php';
if(is_file($base.old){
copy($base.$old, $base.$new);
unlink($base.$old);
}
firman
08-02-2007, 03:44 PM
Sitehatchery?
What yours does above is not what I want?
I want to change whateve is inbetween the slashes to ..
sitehatchery
08-02-2007, 04:25 PM
How about to replace the words in the file?
You said the "words in the file". From this, I thought maybe you were referring to changing the name of the file itself. The derived meaning was a guess and I only had a couple minutes to spit out a solution.
firman
08-02-2007, 06:53 PM
Any idea on how to change what is between slashes to .. ?
NogDog
08-02-2007, 09:37 PM
$file = 'me/you/this/that/open.php';
$dots = preg_replace('#[^/]+/#', '../', $file);
echo $dots;
Outputs:
../../../../open.php
MrCoder
08-03-2007, 08:13 AM
What is the difference between using "/" or "#" in preg?
Is '#[^/]+/#' different to '/[^/]+//'?
NogDog
08-03-2007, 03:36 PM
What is the difference between using "/" or "#" in preg?
Is '#[^/]+/#' different to '/[^/]+//'?
There is no functional difference, other than that by selecting "#" as my regex delimiter, I now do not have to escape the "/" characters in the pattern, making it just a bit less to type and more importantly easier to read. If I had used '/' as the delimiter, then the regex would have been:
'/[^\/]+\//'