How to manipulate my string using regex in php? - php

I have a string as below
$str = '"Mark Zuckerberg" facebook "A social utility connecting friends" profile';
I want it to be manipulated as follows
$output = '"Mark Zuckerberg" OR facebook OR "A social utility connecting friends" OR profile';
What I am trying to have in output is all the units combined with OR in between them. Here a unit is wither a single word when its not in double quotes or the complete string that falls within the single quotes.
I wanted to try with preg_replace. But am unable to get a correct regular expression to match. Kindly help!

$result = preg_replace('/ (?=(?:[^"]*"[^"]*")*[^"]*$)/', ' OR ', $subject);
works if you don't have any escaped quotes in your string. It replaces spaces only if they are followed by an even number of double quotes.

Any reason why preg_replace rather than a simple
$output = '"'.implode('" OR "',str_getcsv($str,' ')).'"';

Related

exploding a search string

I'm trying to make a search string, which can accept a query like this:
$string = 'title -launch category:technology -tag:news -tag:"outer space"$';
Here's a quick explanation of what I want to do:
$ = suffix indicating that the match should be exact
" = double quotes indicate that the multi-word is taken as a single keyword
- = a prefix indicating that the keyword is excluded
Here's my current parser:
$string = preg_replace('/(\w+)\:"(\w+)/', '"${1}:${2}', $string);
$array = str_getcsv($string, ' ');
I was using this above code before, but it doesn't work as intended with the keywords starting on searches like -tag:"outer space". The code above doesn't recognize strings starting with - character and breaks the keyword at the whitespace between the outer and space, despite being enclosed with double quotes.
EDIT: What I'm trying to do with that code is to preg_replace -tag:"outer space" into "-tag:outer space" so that they won't be broken when I pass the string to str_getcsv().
You may use preg_replace like this:
preg_replace('/(-?\w+:)"([^"]+)"/', '"$1$2"', $str);
See the PHP demo online.
The regex matches:
(-?\w+:) - Capturing group 1: an optional - (? matches 1 or 0 occurrences), then 1+ letters/digits/underscores and a :
" - a double quote (it will be removed)
([^"]+) - Capturing group 2: one or more chars other than a double quote
" - a double quote
The replacement pattern is "$1$2": ", capturing group 1 value,
capturing group 2 value, and a ".
See the regex demo here.
Here's how I did it:
$string = preg_replace('/(\-?)(\w+?\:?)"(\w+)/', '"$1$2$3', $string);
$array = str_getcsv($string, ' ');
I considered formats like -"top ten" for quoted multi-word keywords that doesn't have a category/tag + colon prefix.
I'm sorry for being slow, I'm new on regex, php and programming in general and this is also my first post in stackoverflow. I'm trying to learn it as a personal hobby. I'm glad that I learned something new today. I'll be reading more about regex since it looks like it can do a lot of stuff.

php pregmatch_all url with specific word between double quotes

I am having a very hard time coming up with a regex that works in this situation.
I am trying to use pregmatch_all to capture the url between quotes which contain "720.mp4" resulting in the url without the double quotes.
[{"file":"https:\/\/cw012.videohost.com\/files\/videos\/2017\/09\/18\/1505738417e8b76-720.mp4?h=33wg3l1i1G0XcJxvT82x7Q&ttl=1505769928",
In the end i want the above to result as
https:\/\/cw012.videohost.com\/files\/videos\/2017\/09\/18\/1505738417e8b76-720.mp4?h=33wg3l1i1G0XcJxvT82x7Q&ttl=1505769928
Any ideas ? I am very new to regex, i have done my reading but cant put what i have read to work with this specific case.
As a simple approach you can use:
preg_match_all('#"([^"]*720\.mp4[^"]*)"#', $str, $m);
var_dump($m[1]);
The steps are straightforward. We want a literal ". Then we open a capture group ((), then anything that is not a ", then the literal string 720.mp4 (with an escaped dot, because . has a special meaning). Again anything but ", close the group, and a final ".
$m[1] is the content of the capture group we want. $m[0] contains the entire match with the quotes.

php regex white space ignore quotes

Using php and regex, I need to split up a string of data into pieces with the following requirements.
Split it on white space
Ignore whitespace within quotes.
For example:
$string='tid:1212121'; - should just return a single array with "tid:1212121"
$string='tid:1211 topic:ted title:"This Title"'; should return an array with
3 pieces tid:1211, topic:ted and title:"This Title".
I've looked around but my personal regex capabilities are horrible. Also I cannot control the input so the quotes will not be escaped. The string will be as quoted above or longer such as $string='tid:1211 topic:ted title:"This Title" lid:332 fid:"another bit of text"';
Thank you!
If every quoted is preceded by non space characters this could help you:
preg_match_all('/([^ ]*("[^"]*")[\s])|([^ ]+[\s])/', $string, $matches);
You can see in action at : phpliveregex and selecting preg_match_all

Regex to remove single quotes inside single quotes inside text

I have some plain text used to generate html, this is the text:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string'with'bad'quotes'');">
lots of stuff
The structure of the text is always the same because that text is in turn generated, but the last string used as an argument to the javascript function can change, it may have any number of single quotes or not at all. I want to replace those quotes with \' so that the result is:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string\'with\'bad\'quotes\'');">
lots of stuff
I got this far:
onclick="javascript:do_things\('.*', '(.*)'\)
which gives me this match:
string'with'bad'quotes'
But I haven't been able to match the quotes inside, I mean, I could match a quote with .*'.*, but how do I match any number of quotes in any position?
Thanks
How about this?
$string = 'lots of stuff
<a onclick="javascript:do_things(\'http://somelink.to.something.com\', \'string\'with\'bad\'quotes\'\');">
lots of stuff';
echo preg_replace_callback('~(<a\h*onclick="javascript:do_things\(\'.*?\',\h*\')(.*)(\'\);">)~', function($match){
return $match[1] . str_replace("'", "\'", $match[2]) . $match[3];}, $string);
Output:
lots of stuff
<a onclick="javascript:do_things('http://somelink.to.something.com', 'string\'with\'bad\'quotes\'');">
lots of stuff
Regex101 Demo: https://regex101.com/r/rM5mM3/3
We capture the second part of the function then execute a replacement on all single quotes in the found string.

Remove apostrophe from a string using php [duplicate]

This question already has answers here:
How do I replace certain parts of my string?
(5 answers)
Closed last month.
Is there a anyway to remove apostrophe from a string in php?
example:- If string is Mc'win then it should be shown as Mcwin
$Str = "Mc'win";
/*
some code to remove the apostrophe
*/
echo $Str; // should display Mcwin
You can use str_replace.
$Str = str_replace('\'', '', $Str);
or
$Str = str_replace("'", '', $Str);
This will replace all apostrophes with nothing (the 2nd argument) from $Str. The first example escapes the apostrophe so str_replace will recognize it as the character to replace and not part of the enclosure.
If your variable has been sanitized, you may be frustrated to find you can't remove the apostrophe using $string = str_replace("'","",$string);
$string = "A'bcde";
$string = filter_var($string, FILTER_SANITIZE_STRING);
echo $string." = string after sanitizing (looks the same as origin)<br>";
$string = str_replace("'","",$string);
echo $string." ... that's odd, still has the apostrophe!<br>";
This is because sanitizing converts the apostrophe to ' , but you may not notice this, because if you echo the string it looks the same as the origin string.
You need to modify your replace search characters to '
which works after sanitizing.
$string = str_replace("'","",$string);
in my case, i got single quote issue when i wanted to store it to database (in my case MySQL). So, i remove the single quotes using this method
str_replace("'", "", trim($_GET["message"]))
But, the problems comes. Some data required us to have single quotes. So, instead of removing the quotes I try to save the single quotes (escaping single quotes) so it can be used in the future (in my case at Android)
My Idea is to replace from ' to ''.
So here is the final
$content = str_replace("'", "''", trim($_GET["message"])); // double quotes for escape single quotes
This answer is for someone that persist problem like me. I got better solution. Cheers!

Categories