Variable inside regular expression php - php

I a stuck with regular expression and i need help.
So basically i want to do somethning like this:
$data = "hi";
$number = 4;
$reg = '/^[a-z"]{1,4}$/';
if(preg_match($reg,$data)) {
echo 'Match';
}else {
echo 'No match';
}
But i want to use variable
$reg = '/^[a-z"]{1, variable here }$/';
I have tried:
$reg = '/^[a-z"]{1, '. $number .'}$/';
$reg = "/^[a-z\"]{1, $number}$/";
But not getting right result.
Tnx for help

In the first example you have space where you shouldn't have one,
you have:
$reg = '/^[a-z"]{1, '. $number .'}$/';
your should have:
$reg = '/^[a-z"]{1,'. $number .'}$/';
then it works just fine
Update: You have same error in second example - thanks to AbraCadaver

Another way to use variables in regex is through the use of sprintf.
For example:
$nonWhiteSpace = "^\s";
$pattern = sprintf("/[%s]{1,10}/",$nonWhiteSpace);
var_dump($pattern); //gives you /[^\s]{1,10}/

Related

How can I split html value and normal string into different array in php?

Say I have string such as below:
"b<a=2<sup>2</sup>"
Actually its a formula. I need to display this formula on webpage but after b string is hiding because its considered as broken anchor tag. I tried with htmlspecialchars method but it returns complete string as plain text. I am trying with some regex but I can get only text between some tags.
UPDATE:
This seems to work with this formula:
"(c<a) = (b<a) = 2<sup>2</sup>"
And even with this formula:
"b<a=2<sup>2</sup>"
HERE'S THE MAGIC:
<?php
$_string = "b<a=2<sup>2</sup>";
$string = "(c<a) = (b<a) = 2<sup>2</sup>";
$open_sup = strpos($string,"<sup>");
$close_sup = strpos($string,"</sup>");
$chars_array = str_split($string);
foreach($chars_array as $index => $char)
{
if($index != $open_sup && $index != $close_sup)
{
if($char == "<")
{
echo "<";
}
else{
echo $char;
}
}
else{
echo $char;
}
}
OLD SOLUTION (DOESN'T WORK)
Maybe this can help:
I've tried to backslash chars, but it doesn't work as expected.
Then i've tried this one:
<?php
$string = "b&lta=2<sup>2</sup>";
echo $string;
?>
Using &lt html entity it seems to work if i understood your problem...
Let me know
Probably you can give spaces such as :
b < a = 2<sup>2</sup>
It does not disappear the tag and looks much more understanding....
You could try this regex approach, which should skip elements.
$regex = '/<(.*?)\h*.*>.+<\/\1>(*SKIP)(*FAIL)|(<|>)/';
$string = 'b<a=2<sup>2</sup>';
$string = preg_replace_callback($regex, function($match) {
return htmlentities($match[2]);
}, $string);
echo $string;
Output:
b<a=2<sup>2</sup>
PHP Demo: https://eval.in/507605
Regex101: https://regex101.com/r/kD0iM0/1

Fastest way to retrieve part from JSON in my case

Now, I use strstr to get data from external JSON file. I'm not sure if it's the fastest way to do that what I want and I can't test because json_decode don't work in my code.
$before = '"THIS":"';
$after = '","date"';
$data = strstr(substr($url, strpos($url, $before) + strlen($before)), $after, true)
and with json_decode:
$address = file_get_contents('http://json.link/?something=Hello');
$data = json_decode($address);
echo $data->data->THIS;
Now, when I replace my first code with second I get:
Notice: Trying to get property of non-object
All my code:
$text = "a lot of text";
$text_split = array(0 => '');
$number = 0;
$words = explode(' ', $text);
foreach($words as $word)
{
if(strlen($text_split[$number]) + strlen($word) + 1 > 500)
{
++$number;
$text_split[$number] = '';
}
$text_split[$number] .= $word.' ';
}
foreach($text_split as $texts)
{
$text_encode = rawurlencode($texts);
$address = file_get_contents('http://json.link/?something='.$text_encode);
$data = json_decode($address);
echo $data->data->THIS;
}
What should in do in that case? Keep using strstr or replace all code to work with json_decode (maybe because execution time is faster?)? If the second option, how I can make json_decode work here? Thanks!
... and sorry for bad english.
LE:
If I replace $address = file_get_contents('http://json.link/?something='.$text_encode); with $address = file_get_contents('http://json.link/?something=Hello'); I get VALID result for "Hello" text but 10 times. I guess because it's in a foreach.
json_decode is the suggested method to work with JSON data. Here I think you are trying to access an invalid property in JSON object.
$data = json_decode($address);
echo $data->data->THIS;
I guess you need $data->date instead of $data-data?
you have to access the specific key value like this
$json = '{"success":true,"msg":"success","data":{"THIS":"thing I need","date":"24.03.2014","https":false}}';
$d=json_decode($json,true);
echo $d['data']['THIS'];

How to find a string in a variable using PHP and regular expressions

I am trying to find the word and add a number next to it. How could he do? I tried with the code below, but I could not. Could anyone help me?
Thank you!
$string = 'I220ABCD I220ABCDEF I220ABCDEFG'
if (preg_match("/I220.*/", $string, $matches)) {
echo $matches[0];
}
Expected result:
I220ABCD9
I220ABCDEF10
I220ABCDEFG11
Use preg_replace_callback instead like this:
$str = 'I220AB FRRRR CD I221ABCDEF I220AB DSFDSF CDEFG';
$repl= preg_replace_callback('~(I220[^\s]+)~', function($m) {
static $i=9;
return $m[1] . $i++;
}, $str);
echo $repl\n"; // I220AB9 FRRRR CD I221ABCDEF I220AB10 DSFDSF CDEFG
I dont know what your requirnments for adding the number at the end are so i just incremeneted during the loop;
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
$arrayStrings = explode(" ", $string);
$int = 9;
$newString = '';
foreach($arrayStrings as $stringItem)
{
if (preg_match("/I220.*/", $stringItem, $matches))
{
$stringItem = $stringItem.$int;
$newString = $newString.$stringItem." ";
$int++;
}
}
echo $newString;
Use preg_replace_callback():
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
// This requires PHP5.3+ since it's using an anonymous function
$result = preg_replace_callback('/I220[^\s]*/', function($match){
return($match[0].rand(0,10000)); // Add a random number between 0-10000
}, $string);
echo $result; // I220ABCD3863 I220ABCDEF5640 I220ABCDEFG989
Online demo.
You'll need to use a catch block in your regex e.g. "/I220([^ ]+)/" and if you want them all, you'll need to use preg_match_all, too.
preg_replace_callback with your needs:
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
class MyClass{
private static $i = 9;
private static function callback($matches){
return $matches[0] . self::$i++;
}
public static function replaceString($string){
return preg_replace_callback('/I220[^\s]+/',"self::callback",$string);
}
}
echo(MyClass::replaceString($string));
of course you can edit to class to initialize the way you want

PHP String Replacement

I wish to have one string that contains for instance (mystring):
file config.php
$mystring = "hello my name is $name and i got to $school";
file index.php
include('config.php');
$name = $_GET['name'];
$school = $_GET['school'];
echo $mystring;
Would this work ? or are there any better ways
$string = 'Hello, my name is %s and I go to %s';
printf($string, $_GET['name'], $_GET['school']);
or
$string = 'Hello, my name is :name and I go to :school';
echo str_replace(array(':name', ':school'), array($_GET['name'], $_GET['school']), $string);
You can automate that last one with something like:
function value_replace($values, $string) {
return str_replace(array_map(function ($v) { return ":$v"; }, array_keys($values)), $values, $string);
}
$string = 'Hello, my name is :name and I go to :school';
echo values_replace($_GET, $string);
No it won't work.
You have to define $name first before using it in another variable
config.php should look like
<?php
$name = htmlspecialchars($_GET['name']);
$school = htmlspecialchars($_GET['school']);
$mystring = "hello my name is $name and i got to $school";
and index.php like
<?php
include('config.php');
echo $mystring;
Why didn't you try it?
demo:
http://sandbox.phpcode.eu/g/2d9e0.php?name=martin&school=fr.kupky
Alternatively, you can use sprintf like this:
$mystring = "hello my name is %s and i got to %s";
// ...
printf($mystring, $name, $school);
This works because your $mystring literal is using double quotes, if you'd used single quotes then it would not work.
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

Grab variable from php URL string

What's the easiest way to grab a 6-character id from a string?
The id will always be after www.twitpic.com/ and will always be 6 characters.
e.g., $string = 'The url is http://www.twitpic.com/f1462i. Enjoy.';
$id = 'f1462i';
Thanks.
Here you go. Complete working code without regex :
<?php
$string = 'The url is http://www.twitpic.com/f1462i. Enjoy.';
$id = substr($string, strpos($string, 'http://www.twitpic.com/')+23, 6);
echo $id; //output: f1462i
?>
$string = "http://www.twitpic.com/f1462i" ;
$id = substr($string,strpos($string, 'twitpic.com')+strlen('twitpic.com')+1,6) ;
echo $id ;
preg_match("#twitpic\.com/(\w{6})#", "The url is http://www.twitpic.com/f1462i. Enjoy.", $m);
$id = $m[1];

Categories