Replace all occurrences of \\ not starting with - php

This should be simple. I want to change all of these substrings:
\\somedrive\some\path
into
file://\\somedrive\some\path
but if substrings already have a file:// then I don't want to append it again.
This doesn't seem to do anything:
var_export( str_replace( '\\\\', 'file://\\\\', '\\somedrive\some\path file://\\somedrive\some\path' ) );
What am I doing wrong? Also, the above doesn't take into test for file:// already being there; what's the best way of dealing with this?
UPDATE test input:
$test = '
file://\\someserver\some\path
\\someotherserver\path
';
test output:
file://\\someserver\some\path
file://\\someotherserver\path
Thanks.

You should consider escape sequence in string also.
if((strpos($YOUR_STR, '\\\\') !== false) && (strpos($YOUR_STR, 'file://\\\\') === false))
var_export( str_replace( '\\\\', 'file://\\\\', $YOUR_STR ) );

Use a regular expression to check if the given substring starts with file://. If it does, don't do anything. If it doesn't, append file:// at the beginning of the string:
if (!preg_match("~^file://~i", $str)) {
$str = 'file://' . $str;
}
As a function:
function convertPath($path) {
if (!preg_match("~^file://~i", $path)) {
return 'file://'.$path;
}
return $path;
}
Test cases:
echo convertPath('\\somedrive\some\path');
echo convertPath('file://\\somedrive\some\path');
Output:
file://\somedrive\some\path
file://\somedrive\some\path

EDIT
For multiple occurrences : preg_replace('#((?!file://))\\\\#', '$1file://\\\\', $path)

This will work to give you the output you are expecting. As php.net says double slash will be converted into single slash.
if (!preg_match('/^file:\/\//', $str)) {
$str = "file://\\".stripslashes(addslashes($str));
}

Please try this:
$string = "\\somedrive\some\path";
$string = "\\".$string;
echo str_replace( '\\\\', 'file://\\\\',$string);

Related

PHP how to use preg_replace to replace (90) in a string

I have a big problem understanding how to use preg_replace.
I need to replace the string FROM:
GPCNT2(90)>GPBRL2(90)>GPDUT1(180)>GPJDPR TO: GPCNT2>GPBRL2>GPDUT1>GPJDPR
What regular expression should I use to accomplish this?
Current code:
if(strpos($route_path, '/(\d+)/') !== false) {
$route_path = preg_replace('/(\d+)/', '', $route_path);
echo "<br>" .$route_path."</br>";
}
Instead of strpos, use preg_match. You also need to escape the parenthesis \(
here you go:
<?php
$route_path = "GPCNT2(90)>GPBRL2(90)>GPDUT1(180)>GPJDPR";
if(preg_match('/\(\d+\)/', $route_path)) {
$route_path = preg_replace('/\(\d+\)/', '', $route_path);
echo "<br>" .$route_path."</br>";
}
//</br>GPCNT2>GPBRL2>GPDUT1>GPJDPR</br>
Ideone Demo
Is GPCNT2(90)>GPBRL2(90)>GPDUT1(180)>GPJDPR a String? If it is; then you may want to try something like this:
<?php
$str = "GPCNT2(90)>GPBRL2(90)>GPDUT1(180)>GPJDPR";
$strFiltered = preg_replace("#(\(\d*\))(>)#i", "$2", $str);
//COMPARE THE RESULTS TO SEE IF ALL IS OK AS YOU DESIRED IT...
var_dump($str);
var_dump($strFiltered);

Code simplification for authorized chars only

I get a string that contains "#string.number (other stuff)".
I want to filter input from start+1 (= ignore the #) until I get something different than alphanumeric or '-', '_', '.'.
Here's my function:
function _isCharAllowed($c)
{
return (ctype_alnum(str_replace(array('-', '_', '.'), '', $c)));
}
$f=1;
while ($this->_isCharAllowed(mb_substr($str, $f, 1)))
$f++;
$key=mb_substr($str, 1, $f-2);
I want two things. First I have a problem with strings containing '-', '_', '.' because it doesn't do want I want: when there's such string, it removes those chars, giving empty string to ctype_alnum() which returns false:
php -r 'echo var_export((ctype_alnum("")), true)."\n";'
And I would like to optimize it.
How would you do?
You can replace them to an allowed character, say a. That way the string will never be empty.
Sidenote: I'm horrified (but not surprised) to hear that ctype_alnum("") returns false. It totally contradicts what the manual says... and the behaviour is even different in some versions: http://3v4l.org/IEtdi
Why not use preg_replace
Example:
$pattern = '/[^a-z0-9\-\_\.]/';
$strs = [
'some_string-with234.a',
'ano^ther-st*ring-with´+º~º'
];
foreach ($strs as $str) {
echo preg_replace($pattern, '', $str) . PHP_EOL;
}

PHP: preg_replace() to get "parent" component of NameSpace

How can I use the preg_replace() replace function to only return the parent "component" of a PHP NameSpace?
Basically:
Input: \Base\Ent\User; Desired Output: Ent
I've been doing this using substr() but I want to convert it to regex.
Note: Can this be done without preg_match_all()?
Right now, I also have a code to get all parent components:
$s = '\\Base\\Ent\\User';
print preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Ent
But I only want to return Ent.
Thank you!
As Rocket Hazmat says, explode is almost certainly going to be better here than a regex. I would be surprised if it's actually slower than a regex.
But, since you asked, here's a regex solution:
$path = '\Base\Ent\User';
$search = preg_match('~([^\\\\]+)\\\\[^\\\\]+$~', $path, $matches);
if($search) {
$parent = $matches[1];
}
else {
$parent = ''; // handles the case where the path is just, e.g., "User"
}
echo $parent; // echos Ent
I think maybe preg_match might be a better choice for this.
$s = '\\Base\\Ent\\User';
$m = [];
print preg_match('/([^\\\\]*)\\\\[^\\\\]*$/', $s, $m);
print $m[1];
If you read the regular expression backwards, from the $, it says to match many things that aren't backslashes, then a backslash, then many things that aren't backslashes, and save that match for later (in $m).
How about
$path = '\Base\Ent\User';
$section = substr(strrchr(substr(strrchr($path, "\\"), 1), "\\"), 1);
Or
$path = '\Base\Ent\User';
$section = strstr(substr($path, strpos($path, "\\", 1)), "\\", true);

preg_match(_all) with a rule for every space character

I am trying to create a way of making sure that every space has at least three characters (a-zA-Z and single quotes are allowed) on each side of it. It does exactly that, however only with the first space. Not the rest of them. I tried preg_match_all() to no avail, hence my question/post to you guys.
<?PHP
function validateSpaces($str) {
if ( strpos( $str, ' ' ) !== FALSE && !preg_match( '/(([a-z\']{3,})([ ]{1})([a-z\']{3,}))/i', $str ) )
return FALSE;
return TRUE;
}
echo validateSpaces( 'Hey There' ); // Valid (correct)
echo validateSpaces( 'He There' ); // Invalid (correct)
echo validateSpaces( 'Hey Ther e' ); // Valid (incorrect)
?>
As you can see, the first two examples are working like they should, but the second one validates although the second space only has one character on the right side of it. Which is not what I want.
Any help or attempt to help is greatly appreciated!
Thank you in advance,
Chris.
Last modification, will macth only if we have ony one space (trim string before trying to match it):
^([a-z']{3,} ?)+$
You could explode the string on spaces and check the array's contents.
Not complete solution:
$temb=explode(' ', $str);
$valid=true;
foreach ($temb as $tt) {
if (strlen($tt)<3 || !{a preg_match for the right characters in $tt}) {
$valid=false;
break;
}
}
Use preg_match_all() rather than preg_match(), and compare the number of results with a substr_count($str,' ') to see that every space matches your regexp criteria
How about this - you could combine the patterns into one if performance is an issue; I find more than one level of conditional logic difficult to read:
function validate( $value )
{
$ptn_a = '/(^| )[A-Za-z\']{0,2} /';
$ptn_b = '/ [A-Za-z\']{0,2}($| )/';
if ( preg_match( $ptn_a, $value ) )
return false;
if ( preg_match( $ptn_b, $value ) )
return false;
return true;
}
var_dump( validate('Hey There') );
var_dump( validate('He There') );
var_dump( validate('Hey Ther e') );
function validate($string = '')
{
$regexp = '/([^\w]|^)([\w]{1,2})([^\w]|$)/';
if (strlen(trim($string)) && !preg_match($regexp, $string)) {
return 'TRUE';
}
return 'FALSE';
}
print validate(' ');
print "\n";
print validate('Hey There');
print "\n";
print validate('He There');
print "\n";
print validate('Hey ');
print "\n";
print validate('Hey Ther e');
print "\n";
print validate('Hey Th ere');
This can also help.

PHP substring extraction. Get the string before the first '/' or the whole string

I am trying to extract a substring. I need some help with doing it in PHP.
Here are some sample strings I am working with and the results I need:
home/cat1/subcat2 => home
test/cat2 => test
startpage => startpage
I want to get the string till the first /, but if no / is present, get the whole string.
I tried,
substr($mystring, 0, strpos($mystring, '/'))
I think it says - get the position of / and then get the substring from position 0 to that position.
I don't know how to handle the case where there is no /, without making the statement too big.
Is there a way to handle that case also without making the PHP statement too complex?
The most efficient solution is the strtok function:
strtok($mystring, '/')
NOTE: In case of more than one character to split with the results may not meet your expectations e.g. strtok("somethingtosplit", "to") returns s because it is splitting by any single character from the second argument (in this case o is used).
#friek108 thanks for pointing that out in your comment.
For example:
$mystring = 'home/cat1/subcat2/';
$first = strtok($mystring, '/');
echo $first; // home
and
$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home
Use explode()
$arr = explode("/", $string, 2);
$first = $arr[0];
In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.
$first = explode("/", $string)[0];
What about this :
substr($mystring.'/', 0, strpos($mystring, '/'))
Simply add a '/' to the end of mystring so you can be sure there is at least one ;)
Late is better than never. php has a predefined function for that. here is that good way.
strstr
if you want to get the part before match just set before_needle (3rd parameter) to true
http://php.net/manual/en/function.strstr.php
function not_strtok($string, $delimiter)
{
$buffer = strstr($string, $delimiter, true);
if (false === $buffer) {
return $string;
}
return $buffer;
}
var_dump(
not_strtok('st/art/page', '/')
);
One-line version of the accepted answer:
$out=explode("/", $mystring, 2)[0];
Should work in php 5.4+
This is probably the shortest example that came to my mind:
list($first) = explode("/", $mystring);
1) list() will automatically assign string until "/" if delimiter is found
2) if delimiter "/"is not found then the whole string will be assigned
...and if you get really obsessed with performance, you may add extra parameter to explode explode("/", $mystring, 2) which limits maximum of the returned elements.
The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..
But if you're not using 5.3, then the function below should work accurately:
function strbstr( $str, $char, $start=0 ){
if ( isset($str[ $start ]) && $str[$start]!=$char ){
return $str[$start].strbstr( $str, $char, $start+1 );
}
}
I haven't tested it though, but this should work just fine.. And it's pretty fast as well
You can try using a regex like this:
$s = preg_replace('|/.*$|', '', $s);
sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.
Using current on explode would ease the process.
$str = current(explode("/", $str, 2));
You could create a helper function to take care of that:
/**
* Return string before needle if it exists.
*
* #param string $str
* #param mixed $needle
* #return string
*/
function str_before($str, $needle)
{
$pos = strpos($str, $needle);
return ($pos !== false) ? substr($str, 0, $pos) : $str;
}
Here's a use case:
$sing = 'My name is Luka. I live on the second floor.';
echo str_before($sing, '.'); // My name is Luka
$arr = explode("/", $string, 2); $first = $arr[0];
This Way is better and more accurate than strtok
because if you wanna get the values before # for example
while the there's no string before # it will give you whats after the sign .
but explode doesnt
$string="kalion/home/public_html";
$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));
why not use:
function getwhatiwant($s)
{
$delimiter='/';
$x=strstr($s,$delimiter,true);
return ($x?$x:$s);
}
OR:
function getwhatiwant($s)
{
$delimiter='/';
$t=explode($delimiter, $s);
return ($t[1]?$t[0]:$s);
}

Categories