I'm working with the mailgun API and webhooks. Sometimes the message-id will include < and > but other times it wont.
In my controller, I am trying to check if the message-id contains < and > and if so then remove it and store that in a variable.
I may need to use rtrim or str_replace but I'm not sure if there is a better way to do this? Maybe regex?
Here is an example of one mailgun returns when the event is delivered:
<20180203002650.1.EEE3119CC37C5A82#domain.com>
Here is one when mailgun returns when the event is opened. (notice it is the same message ID now it does not contain < and >
20180203002650.1.EEE3119CC37C5A82#domain.com
Links:
Mailgun API,
rtrim,
str_replace
The trim function (to be exact, its overload that takes two arguments) can do the job pretty quickly and pretty well. In my opinion, using a regular expression in this case is an overkill.
<?php
$str = '<20180203002650.1.EEE3119CC37C5A82#domain.com>';
$str_trimmed = trim($str, '<>');
echo $str_trimmed; // 20180203002650.1.EEE3119CC37C5A82#domain.com
?>
You can see a working demo here.
this function should do what you need.
$str = '<20180203002650.1.EEE3119CC37C5A82#domain.com>';
$cleanString = preg_replace_callback(
'/<|>|and/',
function ($matches) {
return "";
},
$str
);
echo $cleanString;
Related
<?php
$string="I am Azizul hakim.I am a student.I am feeling good today";
$find="am";
$i=0;
$find_length=strlen($find);
while($i<strlen($string))
{
$pos=strpos($string,$find,$i);
echo $pos;
$i=$pos+$find_length;
}
?>
The php code is executing infinite times.Although the limit is restricted by specifying the string length of the string.Why it is executing infinite times?
strpos returns false, which evaluates to 0, when your remaining $string doesn't contain $find and the loop starts over again.
In cases like this, I believe perl compatible regular expression, (pcre), is always the best choice. Why, because you will use only (1) function / method call, and then simple loop to process the result. With string type functions / methods, each time your $needle is found in your $haystack you will need to call another string type function / method to handle the next occurrence of your $needle being found in your $haystack!
I've read through multiple tutorials on regex and it's associated functions but I am stumped on this one.
I have a really simple replace that looks for a specific delimiter and parses the name of a PHP variable. Here it is:
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $this->file));
I keep getting errors about php not liking the #1 in ${$1}. Fair enough, can't start a variable name with a number, I knew that...
So I tried:
var_dump(preg_replace('/{{\$(.*?)}}/', ${'$1'}, $this->file));
Same thing.
Yet if I try:
var_dump(preg_replace('/{{\$(.*?)}}/', '$1 yo', $this->file));
It works...
So, how do I get php to echo a variable named whatever $1 is.
For example:
$hola = yo;
$string = hello{{$hola}}hello{{$hola}};
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $string));
And the output would be:
helloyohelloyo
Spank you!
EDIT
I should also mention that I am aware that there is a standard recommendation on how to match php variables with regex, but i'd like to get it working with a regex that I fully understand first.
Like so:
$hola = 'yo';
$string = 'hello{{$hola}}hello{{$hola}}';
$result = preg_replace_callback('/\{\{\$(.*?)\}\}/', function ($matches) use ($hola) {
return ${$matches[1]};
}, $string);
var_dump($result);
preg_replace_callback calls a callback on every match.
In order to use the $hola variable inside the callback you need to explicitly make it available inside the function (use ($hola)).
All this said... I don't get it. What this code does is essentially what PHP already does out-of-the-box.
$hola = 'yo';
$string = "hello{$hola}hello{$hola}";
echo $string; // "helloyohelloyo"
Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().
Usually I use trim() PHP function to check, if data is not empty. Also for MySQL I use mysql_real_escape_string(). Is this enough,or do I need to perform additional checks?
To check if data is "empty", you can use empty().
Yes, to escape data you use mysql_real_escape_string() for MySQL. By default, trim() is used to trim trailing and leading whitespace, if used without additional parameters.
Is it so hard to check on manual what each function does?
I usually do this:
$foo = isset($_POST['bar']) ? trim($_POST['bar']) : '';
if (!empty($foo))
$db->query("UPDATE table SET foo = '".mysql_real_escape_string($foo)."'");
if (!empty($_POST['data']) && other controls) {
// Success
$data = mysql_real_escape_string($data)
$sql = "SELECT * FROM users WHERE data = '$data'";
mysql_query($sql);
}
I tend to use isset($_POST['key1'], $_POST['key2'], $_POST['keyn']) as a starting point for determining if a form has had all required data submitted, along with testing things such as $_SERVER['REQUEST_METHOD'], $_SERVER['SERVER_PORT'], $_SERVER['REQUEST_URI']. Trimming is not harmful, but I just go for the jugular with preg_match($needle, $haystackenter) and make the regular expression non-greedyand non-buffer capturing. In short, why condition input when you can just make the test fail to being with?
The language construct empty() works, but does it really matter if the value doesn't match the pattern you are looking for? As for performance, who can say if someone copied and pasted the Oxford English Dictionary what would happen in either case.
function ValidatePostKeyAndValue($input, $pattern, $length)
{
if(isset($input) &&
preg_match($pattern, $input) &&
ctype_print($input) &&
strlen($input) <= $length &&
is_string($input))
{
return true;
}
else
{
return false;
}
}
I could do more or less, depending on the situation. Boolean functions are your friends.
As far your $data variable, I think it would be wise to consider if the wildcards _ and % might appear in your data. If so, addcslashes() can be used to target those characters in your string. Over all though, moving to mysqli() will save you from having to use mysql_select_db(). mysqli_connect() does this for you! Well worth the switch.
I know this is a really simple question, but I was just wondering if there is a native php method to inject a string into another string. My usual response to a new text manipulation is to consult the manual's listings of string functions. But I didn't see any native methods for explicitly inserting a string into another string so I figured i'd consult SO.
The answer is likely some kind of combination of the php native string functions OR simply regex (which makes my eye's bleed and my brain melt so I avoid it).
EX:
Take a string like some-image.jpg and inject .big before .jpg yielding some-image.big.jpg
You can use substr_replace to insert a string by replacing a zero-length substring with your insertion:
$string = "some-image.jpg";
$insertion = ".big";
$index = 10;
$result = substr_replace($string, $insertion, $index, 0);
From the manual page (the description of the length (4th) argument):
If length is zero then this function will have the effect of inserting replacement into string at the given start offset.
You can do anything with regular expressions!
For your specific request, the solution would be:
$var = 'myimage.jpg';
$new_var = preg_replace('/\.jpg$/', '.big$0', $var);
I would suggest reading up on how to write regular expressions, as they can be very useful in development (here's a starting point).
See this: http://www.krizka.net/2007/12/29/how-to-insert-a-string-into-another-string-in-php/
$newstring=substr_replace($orig_string, $insert_string, $position, 0);