How to allow several values in regexp submask - php

I want to pull some values out of string (in function)
if(!preg_match('/(.+)\.([0-9]*)x([0-9]*)(w|wr|r)?\.([^\.]+)$/', $filename, $matches))
return false;
$file = $matches[1];
$width = $matches[2];
$height = $matches[3];
$set_watermark_or_nonconstrain = $matches[4]; // that's what I need to fix
$ext = $matches[5];
However, if I set string like {$image[0]->filename|resize:614:300:r} (Smarty), all goes well except that $set_watermark_or_nonconstrain is always 'w'. What do I need to set instead of w|wr|r to pull 'w', 'wr' or 'r' from this submask? Thanks!

Using the string example you have given, the following expression does what you are looking for
$string = '{$image[0]->filename|resize:614:300:r}';
if(preg_match('/\{([^\|]+)\|[^:]+:(\d+):(\d+):([^}]+)/', $string, $m)){
echo 'm1: '.$m[1] ."<br />\n";
echo 'm2: '.$m[2] ."<br />\n";
echo 'm3: '.$m[3] ."<br />\n";
echo 'm4: '.$m[4] ."<br />\n";
}
Which produces the following ouput:
m1: $image[0]->filename
m2: 614
m3: 300
m4: r

Related

Getting variables between slash forwards in a URL

Let's say I have a URL: https://somesite.com/0/posts/20/290/755653-Title.html How would I get these variables: /0/, /20/, /290/ ? Note they are variables, they will always be different.
I thought I could get them like so:
$url = '//somesite.com/0/posts/20/290/755653-Title.html';
var_dump(parse_url($url));
but the array doesn't show them as separate variables. Should it be done with a preg_replace instead? I don't think I know how. Thank you for your help.
One option is to use a positive lookahead with preg_match_all where you capture the pattern in a capturing group:
(?=(/\d+/))
That will match
(?= Positive lookahead, assert what is directly on the right is
(/\d+/) Match /, 1+ digits and /
) Close positive lookahead
Regex demo | Php demo
For example
$re = '~(?=(/\d+/))~m';
$str = 'https://somesite.com/0/posts/20/290/755653-Title.html';
preg_match_all($re, $str, $matches);
print_r($matches[1]);
Result
Array
(
[0] => /0/
[1] => /20/
[2] => /290/
)
If you want to get the digits only without the surrounding slashes you could add the group around the digits only
(?=/(\d+)/)
Php demo
You could use explode() and turn the string into an array divided by the "/" delimiter.
<?php
// Example 1
$url = "https://somesite.com/0/posts/20/290/755653-Title.html";
$pieces = explode("/", $url);
echo $pieces[0] . "<br />";
echo $pieces[1] . "<br />";
echo $pieces[2] . "<br />";
echo $pieces[3] . "<br />";
echo $pieces[4] . "<br />";
echo $pieces[5] . "<br />";
echo $pieces[5] . "<br />";
echo $pieces[6] . "<br />";
echo $pieces[7] . "<br />";
echo "<hr />";
// Example 2
$data = "https://somesite.com/0/posts/20/290/755653-Title.html";
list($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth) = explode("/", $url);
echo $first . "<br />";
echo $second . "<br />";
echo $third . "<br />";
echo $fourth . "<br />";
echo $fifth . "<br />";
echo $sixth . "<br />";
echo $seventh . "<br />";
echo $eighth . "<br />";
?>
Output:
https:
somesite.com
0
posts
20
20
290
755653-Title.html
https:
somesite.com
0
posts
20
290
755653-Title.html
We can try splitting on path separator, and then using array_filter with an inline function to retain only purely numerical components:
$str = 'https://somesite.com/0/posts/20/290/755653-Title.html';
$parts = explode("/", $str);
$parts = array_filter($parts, function($item) { return is_numeric($item); });
print_r($parts);
This prints:
Array
(
[3] => 0
[5] => 20
[6] => 290
)
Note that this approach completely avoids the use of a formal regex, which might have performance implications if you needed to do this often in your script.

check the same char in strg and remove and split from underscore in PHP?

Hello I have one string "22A_n22A" and i want to remove the same character from this string and want to split from "_" to two string like 22A and n22A.
i tried it but did not get any solution.
final out put i want like 22A_n22A to (n)22AA
<?php
function conti($str,$case_sensitive = false) {
//if($com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $newval))
if(strcmp($case_sensitive , $case_sensitive) === 0 )
{
$pieces = explode("_", $str);
$str1 = $pieces[0];
$str2 = $pieces[1];
$ary1 = str_split($str1);
$ary2 = str_split($str2);
if (isset($case_sensitive))
{
$ary1 = array_map('strtolower',$ary1);
$ary2 = array_map('strtolower',$ary2);
}
$com = implode('',array_intersect($ary1,$ary2));
$diff = implode('',array_merge(array_diff($ary1, $ary2),array_diff($ary2, $ary1)));
$int = (int) filter_var($com, FILTER_SANITIZE_NUMBER_INT);
$onlystr = preg_replace('/\d/', '', $com);
$newval= '('.$diff.')'.$int.$onlystr.$onlystr;
// $com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $str);
echo '<pre><h1>';
echo 'new value:';
print_r($newval);
echo "<br>";
echo "<br>";
echo "<br>";
echo 'new value:';
print_r($com);
echo "<br>";
echo 'new diff:';
print_r($diff);
echo '</pre>';
return $newval;
}
else {
echo '<pre><h1>';
echo 'oldvalue:';
print_r($str);
echo '</pre>';
return $str;
}
}
echo(conti('71A_n71A'));
// echo(conti('66A_n66A'));
?>
As stated in your comments your requirement is to:
Split the string on _
Pluck the last character from the first chunk of the string and append that to the end of the second string
Wrap the first character of the second chunk of the string in parentheses
For example, 65A_n66A becomes (n)66AA.
You can do this with by performing explode() on the original string, extracting the parts you need and piecing them back together in your desired format:
function format($string) {
list($first, $second) = explode('_', $string);
return sprintf('(%s)%s%s',
$second[0],
substr($second, 1),
$first[strlen($first) - 1]
);
}
This yields:
echo format('22A_n22A'); // (n)22AA
echo format('11A_n22B'); // (n)22BA
echo format('65A_n66A'); // (n)66AA
Hope this helps :)

Find words in text, php

How to resolve this problem:
Write a PHP program that finds the word in a text.
The suffix is separated from the text by a pipe.
For example: suffix|SOME_TEXT;
input: text|lorem ips llfaa Loremipsumtext.
output: Loremipsumtext
My code is this, but logic maybe is wrong:
$mystring = fgets(STDIN);
$find = explode('|', $mystring);
$pos = strpos($find, $mystring);
if ($pos === false) {
echo "The string '$find' was not found in the string '$mystring'.";
}
else {
echo "The string '$find' was found in the string '$mystring',";
echo " and exists at position $pos.";
}
explode() returns an array, so you need to use $find[0] for the suffix, and $find[1] for the text. So it should be:
$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);
if ($pos === false) {
echo "The string '$suffix' was not found in '$text'.";
} else {
echo "The string '$suffix' was found in '$text', ";
echo " and exists at position $pos.";
}
However, this returns the position of the suffix, not the word containing it. It also doesn't check that the suffix is at the end of the word, it will find it anywhere in the word. If you want to match words rather than just strings, a regular expression would be a better method.
$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);
if ($found) {
echo echo "The suffix '$suffix' was found in '$text', ";
echo " and exists in the word '$match[0]'.";
} else {
echo "The suffix '$suffix' was not found in '$text'.";
}

What is the simplest way to split this string using PHP?

I have the below string in PHP.
:guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP
I need to create these variables from the string:
$nick = guest
$user = lbjpewueqi
$host = AF8A326D.E0B4A40D.F85DC93A.IP
What is the best function to use to do this?
Ideally I would like to create some sort of function so I can pass to it the string and what part I want returned.
For example:
$string = "guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
echo stringToPart($string, nick);
guest
echo stringToPart($string, nick);
lbjpewueqi
echo stringToPart($string, host);
AF8A326D.E0B4A40D.F85DC93A.IP
Another version:
function stringToPart($string, $part) {
if (preg_match('/^:(.*)!(.*)#(.*)/', $string, $matches)) {
$nick = $matches[1];
$user = $matches[2];
$host = $matches[3];
return isset($$part) ? $$part : null;
}
}
More strict than preg_split solutions - it checks separators order.
Maybe this code may helpful for you
$p = '/[:!#]/';
$s = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
print_r( preg_split( $p, $s ), 1 );
You can declare a function like this:
$s = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
function stringToPart($str, $part) {
$pat['nick'] = '/:(.*)!/';
$pat['user'] = '/.*!(.*)#/';
$pat['host'] = '/#(.*)/';
preg_match($pat[$part], $str, $m);
if (count($m) > 1) return $m[1];
return null;
}
echo stringToPart($s,'nick')."\n";
echo stringToPart($s,'user')."\n";
echo stringToPart($s,'host')."\n";
The below should do what you're looking for.
$pattern = "/[:!#]/";
$subject = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
print_r(preg_split($pattern, $subject));
The pattern is specifying what characters to split on so you could in theory have any amount of characters here if there were other instance you needed to account for different strings being passed in.
To return the values instead of just printing then to the screen use this:
$pattern = "/[:!#]/";
$subject = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
$result = preg_split($pattern, $subject));
$nick = $result[1];
$user = $result[2];
$host = $result[3];
stringToPart(':guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP','nick');
function stringToPart($string, $type){
$result['nick']= substr($string,strpos($string,':')+1,(strpos($string,'!')-strpos($string,':')-1));
$result['user']= substr($string,strpos($string,'!')+1,(strpos($string,'#')-strpos($string,'!')-1));
$result['host']= substr($string,strpos($string,'#')+1);
return $result[$type];
}
<?php
function stringToPart($string, $key)
{
$matches = null;
$returnValue = preg_match('/:(?P<nick>[^!]*)!(?P<user>.*?)#(?P<host>.*)/', $string, $matches);
if (isset($matches[$key]))
{
return $matches[$key];
} else
{
return NULL;
}
}
$string = ':guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP';
echo stringToPart($string, "nick");
echo "<br />";
echo stringToPart($string, "user");
echo "<br />";
echo stringToPart($string, "host");
echo "<br />";
?>

How to get quickly two data from this String data?

There is this String data from the column value of a table column : /var/www/imfmobile/photoj2meupload/7455575/photo32.png
I want to get the 7455575 and the photo32.png substring's. How to achieve that quickly ?
use explode to split the string at /:
$parts = explode('/',$mystring);
and then just use array_pop to get the values:
$filename = array_pop($parts);
$foldername = array_pop($parts);
$str = '/var/www/imfmobile/photoj2meupload/7455575/photo32.png';
$arr = explode('/', $str);
echo end($arr); // photo32.png
echo prev($arr); // 7455575
You might want to look at the pathinfo() and basename() functions:
$path_parts = pathinfo('/var/www/imfmobile/photoj2meupload/7455575/photo32.png');
echo basename( $path_parts['dirname'] ) . "\n";
echo $path_parts['basename'] . "\n";
Will output:
7455575
photo32.png

Categories