This question already has answers here:
How to remove a substring from a string using PHP?
(4 answers)
Closed 7 years ago.
I have this string variable in my PHP code:
I am getting this value from DB.
$includes = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
How to remove this sentence ('Kindly Note: Before 72Hrs Cancellation full refund') from the string.
I have to remove the text which come after this text('Kindly Note:') from the given string How to do that.
Some time I get different text after this text('Kindly Note: We dont allow 24hrs checkin') So I want to remove text whatever comes after this text('Kindly Note:');
Since I love exploding things...try this logic, will remove anything beyond the "Kindly Note:" part:
$includes = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
$arr_includes = explode('Kindly Note:', $includes);
$include = $arr_includes[0];
output:
~ All taxes~ Complimentary Buffet Breakfast,~ Complimentary Wi-Fi~ Complimentary Fruit Basket only for Suite RoomFacilities and Services:~ 24Hrs Room Service~ Lounge~ Direct Dialing STD and ISD facilities
use chop()
echo chop($includes,'Before 72Hrs Cancellation full refund');
or
echo chop($includes,'Kindly Note:<br/>Before 72Hrs Cancellation full refund');
Edit 1
use
echo substr($includes, 0, strpos($includes, "Kindly Note:"));
Use str_replace simply.
str_replace('Kindly Note:<br/>Before 72Hrs Cancellation full refund', '', $includes);
Simple:
if ($dbText === 'your text') {
$dbText = 'your replacement text';
}
or change the text in the database itself. If you need something else, please elaborate on your requirements. Things like string replacement or regular expression replacement come to mind for more generic problems.
If it comes always end of the string the you can use
substr($string, 0, -3);
use str_replace function
$s = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
$new_string = str_replace('<br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund', '', $s);
Assume "Kindly Note:" exists in the string and you want to remove anything after the "Kindly Note:"
echo strstr($includes, "Kindly Note:", true);
Related
Hi am working on some maintenance project. But on that code someone added the preg_match expression for not allowing the toll free numbers.. Toll free numbers start with area codes 800, 888, 877, 866, 855 or 844. They will be formatted as 800-xxx-xxxx or 1-800-xxx-xxxx or (800) xxx-xxxx or 800xxxxxxx or 1800xxxxxxx. etc.
If the number is a toll free number, throw an error "Please enter a local phone number here, not a toll free number."
Below is my code:-
$getphone = $_POST['phone'];
/* ISSUE: This catches
1-800-450-7006
1 (800) 450-7006
1(800) 450-7006
but is not catching
(800) 450-7006
*/
if(!preg_match('/^(?!(?:1-)?(\\$|#|8(00|55|66|77|88)))\(?[\\s.-]*([0-9]{3})?[\\s.-]*\)?[\\s.-]*[0-9]{3}[\\s.-]*[0-9]{4}$/', $getphone)){
// Need to redirect back, not to profile
echo 'Please enter a local phone number here, not a toll free number'; die;
}
Can anyone help me how to check for this case (800) 450-7006. Thanks
I suggest "excluding" specific numbers inside (or not) parentheses at the start:
'~^(?!(?:1-)?(?:\$|#|(?:\((8(?:00|55|66|77|88))\)|(?1))))\(?[\s.-]*([0-9]{3})?[\s.-]*\)?[\s.-]*[0-9]{3}[\s.-]*[0-9]{4}$~'
See the regex demo
I replaced 8(00|55|66|77|88) with (?:\((8(?:00|55|66|77|88))\)|(?1)), a non-capturing group matching two alternatives:
\((8(?:00|55|66|77|88))\) - (, 800, 855, 866, 877, 888 and then )
| - or
(?1) - the whole 8(?:00|55|66|77|88), Group 1, pattern.
<?php
/* 800, 888, 877, 866, 855 or 844. They will be formatted as
800-xxx-xxxx or 1-800-xxx-xxxx or (800) xxx-xxxx or
800xxxxxxx or 1800xxxxxxx */
$phone = $_POST['phone'];
// remove everything that is not a number
$phone = preg_replace('/[^\d]/', '', $phone);
// look for your pattern in the "cleaned" string
if(!preg_match('/^1?8(88|77|66|55|44|00)/', $phone)){
echo 'error';
}
?>
I have a single location field where people can enter whatever they want, but generally they will enter something in the format of "Town, Initials". So for example, these entries...
New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND
would ideally become...
New York, NY
Columbia, SC
Charleston
Washington, DC
Bismarck, ND
Obviously I can use ucfirst() on the string to handle the first character, but these are things I'm not sure how to do (if they can be done at all)...
Capitalizing everything after a comma
Lowercasing everything before the comma (aside from the first character)
Is this easily doable or do I need to use some sort of regex function?
You could simply chop it up and fix it.
<?php
$geo = 'New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND';
$geo = explode(PHP_EOL, $geo);
foreach ($geo as $str) {
// chop
$str = explode(',', $str);
// fix
echo
(!empty($str[0]) ? ucwords(strtolower(trim($str[0]))) : null).
(!empty($str[1]) ? ', '.strtoupper(trim($str[1])) : null).PHP_EOL;
}
https://3v4l.org/ojl2M
Though you should not trust the user to enter the correct format. Instead find a huge list of all states and auto complete them in. Perhaps something like https://gist.github.com/maxrice/2776900 - then validate against it.
So, my text I want to post on Twitter is sometimes more than 140 character, so, I need to check the lenght and then go without changes if less than 140 or slive the text into two pieces (the text and the link) and grab the text part and make it e.g. 100 characters long - chop the rest.
Then grab the - now 100 characters long part - and put it otgether with the url.
How to do that?
my code so far:
if (strlen($status) < 140) {
// continue
} else {
// 1. slice the $status into $text and $url (every message has url so
// checking is not important right now
// 2. shorten the text to 100 char
// something like $text = substr($text, 0, 100); ?
// 3. put them back together
$status = $text . ' ' . $url;
}
How should I change my code? I have biggest problem with the first part when getting the url and text part.
Btw. in each $status is only 1 url, so checking for mulitple urls is not necessary
Example of a text that is longer than it should be:
What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into the Inca Empire during the fifteenth century. The territory was colonized by Spain during the sixteenth century, achieving independence in 1820 as part of Gran Colombia, from which it emerged as its own sovereign state in 1830. The legacy of both empires is reflected in Ecuador's ethnically diverse population, with most of its 15.2 million people being mestizos, followed by large minorities of European, Amerindian, and African descendant. https://en.wikipedia.org/wiki/Ecuador
should become in the end this:
What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated int https://en.wikipedia.org/wiki/Ecuador
If you can be sure that the URL does not contain any spaces (no well-formed URL should) and that it is always present, try it like that:
preg_match('/^(.*)(\\S+)$/', $status, $matches);
$text = $matches[1];
$url = $matches[2];
$text = substr($text, 0, 100);
But possibly the length of the text should be adapted to the length of the url, so you would use
$text = substr($text, 0, 140-strlen($url)-1);
$reg = '/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i';
$string = "What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into the Inca Empire during the fifteenth century. The territory was colonized by Spain during the sixteenth century, achieving independence in 1820 as part of Gran Colombia, from which it emerged as its own sovereign state in 1830. The legacy of both empires is reflected in Ecuador's ethnically diverse population, with most of its 15.2 million people being mestizos, followed by large minorities of European, Amerindian, and African descendant. https://en.wikipedia.org/wiki/Ecuador";
preg_match_all($reg, $string, $matches, PREG_PATTERN_ORDER);
$cut_string = substr($string, 0, (140-strlen($matches[0][0])-1));
$your_twitt = $cut_string . " " . $matches[0][0];
echo $your_twitt;
// ouputs : "What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into t https://en.wikipedia.org/wiki/Ecuador"
This might be what you want :
$status = 'What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into the Inca Empire during the fifteenth century. The territory was colonized by Spain during the sixteenth century, achieving independence in 1820 as part of Gran Colombia, from which it emerged as its own sovereign state in 1830. The legacy of both empires is reflected in Ecuador\'s ethnically diverse population, with most of its 15.2 million people being mestizos, followed by large minorities of European, Amerindian, and African descendant. https://en.wikipedia.org/wiki/Ecuador';
if (strlen($status) < 140) {
echo 'Lenght ok';
} else {
$totalPart = round(strlen($status)/100);
$fulltweet = array();
for ($i=0; $i < $totalPart; $i++) {
if($i==0)
{
$fulltweet[$i] = substr($status, 0,100);
}else{
$fulltweet[$i] = substr($status, $i * 100);
}
}
}
If the string is longer than 140 chars then it'll explode it in an array of 100 char for each row
I want to extract a string between two other strings. The strings happen to be within HTML tags but I would like to avoid a conversation about whether I should be parsing HTML with regex (I know I shouldn't and have solved the problem with stristr() but would like to know how to do it with regular expressions.
A string might look like this:
...uld select “Apply” below.<br/><br/><b>Primary Location</b>: United States-Washington-Seattle<br/><b>Travel</b>: Yes, 75 % of the Time <br/><b>Job Type</b>: Standard<br/><b>Region</b>: US Service Lines: ASL - Business Intelligence<br/><b>Job</b>: Business Intelligence<br/><b>Capability Group</b>: Con/Sol - BI&C<br/><br/>LOC:USA
I am interested in <b>Primary Location</b>: United States-Washington-Seattle<br/> and want to extract 'United States-Washington-Seattle'
I tried '(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)' which worked in RegExr but not PHP:
preg_match("/(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)/", $description,$matches);
You used / as regex delimiter, so you need to escape it if you want to match it literally or use a different delimiter
preg_match("/(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)/", $description,$matches);
to
preg_match("/(?<=<b>Primary Location<\/b>:)(.*?)(?=<br\/>)/", $description,$matches);
or this
preg_match("~(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)~", $description,$matches);
Update
I just tested it on www.writecodeonline.com/php and
$description = "uld select “Apply” below.<br/><br/><b>Primary Location</b>: United States-Washington-Seattle<br/><b>Travel</b>: Yes, 75 % of the Time <br/><b>Job Type</b>: Standard<br/><b>Region</b>: US Service Lines: ASL - Business Intelligence<br/><b>Job</b>: Business Intelligence<br/><b>Capability Group</b>: Con/Sol - BI&C<br/><br/>LOC:USA";
preg_match("~(?<=<b>Primary Location</b>:)(.*?)(?=<br/>)~", $description, $matches);
print_r($matches);
is working. Output:
Array ( [0] => United States-Washington-Seattle [1] => United States-Washington-Seattle )
You can also get rid of the capturing group and do
$description = "uld select “Apply” below.<br/><br/><b>Primary Location</b>: United States-Washington-Seattle<br/><b>Travel</b>: Yes, 75 % of the Time <br/><b>Job Type</b>: Standard<br/><b>Region</b>: US Service Lines: ASL - Business Intelligence<br/><b>Job</b>: Business Intelligence<br/><b>Capability Group</b>: Con/Sol - BI&C<br/><br/>LOC:USA";
preg_match("~(?<=<b>Primary Location</b>:).*?(?=<br/>)~", $description, $matches);
print($matches[0]);
Output
United States-Washington-Seattle
This is the content of one mysql table field:
Flash LEDs: 0.5W
LED lamps: 5mm
Low Powers: 0.06W, 0.2W
Remarks(1): this is remark1
----------
Accessories: Light Engine
Lifestyle Lights: Ambion, Crane Fun
Office Lights: OL-Deluxe Series
Street Lights: Dolphin
Retrofits: SL-10A, SL-60A
Remarks(2): this is remark2
----------
Infrared Receiver Module: High Data Rate Short Burst
Optical Sensors: Ambient Light Sensor, Proximity Sensor, RGB Color Sensor
Photo Coupler: Transistor
Remarks(3): this is remark3
----------
Display: Dot Matrix
Remarks(4): this is remark4
Now, I want to read the remarks and store them in a variable. Remarks(1), Remarks(2), etc. are fixed. 'this is remark1', etc. come from form input fields, so they are flexible.
Basically what I need is: Read everything between 'Remarks(1):' and '--------' and save it in a variable.
Thanks for your help.
You can use regex:
preg_match_all("~Remarks\(([^)]+)\):([^\n]+)~", $str, $m);
As seen on ideone.
The regex will put X in match group 1, Y in match group 2 (Remarks(X): Y)
This would be a job for regular expressions, which allow you to match on exactly the kinds of rules your requirements express. Here is a tutorial for you.
Use preg function for this or otherwise you can explode and implode function to get correct result. Don't Use Substring it may not provide correction.
Example of Implode and Explode Function for your query string :
$sdr = "Remarks(4): this is remark4";
$sdr1 = explode(":",$sdr);
$frst = $sdr1[0];
$sdr2 = array_shift($sdr1);
$secnd = implode(" ", $sdr1);
echo "First String - ".$frst;
echo "<br>";
echo "Second String - ".$secnd;
echo "<br>";
Your Answer :
First String - Remarks(4)
Second String - this is remark4