Extracting part of a string up to a specific character in PHP - php

I have a string containing a name and address lines, with a <br /> tag separating the name and each address line. For instance:
John Smith<br />999 Somewhere Lane<br />City, FL 66600
I want to separate the name from the rest of the address using PHP. Is this something that can be done?

explode or substr with strpos
$str = 'John Smith<br />999 Somewhere Lane<br />City, FL 66600';
echo substr($str,0,strpos($str,'<br />')); //John Smith

In this particular case the simplest would be to use explode:
$str = 'John Smith<br />999 Somewhere Lane<br />City, FL 66600';
$tmp = explode('<br />', $str);
$name = $tmp[0];
You may, of course use regex but this is simpler.

This should give you the data even though it looked like this <br>, <br/> <br />, etc.
$text = "John Smith<br />999 Somewhere Lane<br />City, FL 66600"
$data = preg_split("/\<br(\s+)?(\/)?\>/", $text);
print_r($data);
Array
(
[0] => John Smith
[1] => 999 Somewhere Lane
[2] => City, FL 66600
)

Related

php regular expression parse data

I have a field which contain 20 character (pad string with space character from right) like below:
VINEYARD HAVEN MA
BOLIVAR TN
,
BOLIVAR, TN
NORTH TONAWANDA, NY
How can I use regular expression to parse and get data, the result I want will look like this:
[1] VINEYARD HAVEN [2] MA
[1] BOLIVAR [2] TN
[1] , or empty [2] , or empty
[1] BOLIVAR, or BOLIVAR [2] TN or ,TN
[1] NORTH TONAWANDA, or NORTH TONAWANDA [2] NY or ,NY
Currently I use this regex:
^(\D*)(?=[ ]\w{2}[ ]*)([ ]\w{2}[ ]*)
But it couldnot match the line:
,
Please help to adjust my regex so that I match all data above
What about this regex: ^(.*)[ ,](\w*)$ ? You can see working it here: http://regexr.com/3cno7.
Example usage:
<?php
$string = 'VINEYARD HAVEN MA
BOLIVAR TN
,
BOLIVAR, TN
NORTH TONAWANDA, NY';
$lines = array_map('trim', explode("\n", $string));
$pattern = '/^(.*)[ ,](\w*)$/';
foreach ($lines as $line) {
$res = preg_match($pattern, $line, $matched);
print 'first: "' . $matched[1] . '", second: "' . $matched[2] . '"' . PHP_EOL;
}
It's probably possible to implement this in a regular expression (try /(.*)\b([A-Z][A-Z])$/ ), however if you don't know how to write the regular expression you'll never be able to debug it. Yes, its worth finding out as a learning exercise, but since we're talking about PHP here (which does have a mechanism for storing compiled REs and isn't often used for bulk data operations) I would use something like the following if I needed to solve the problem quickly and in maintainable code:
$str=trim($str);
if (preg_match("/\b[A-Z][A-Z]$/i", $str, $match)) {
$state=$match[0];
$town=trim(substr($str,0,-2)), " ,\t\n\r\0\x0B");
}

Splitting a string by comma while ignoring other commas (not quoted)

I am working with an API and getting results via an API. I am having trouble with the delimitation to split the array. Below is the sample example data I am receiving from the API:
name: jo mamma, location: Atlanta, Georgia, description: He is a good
boy, and he is pretty funny, skills: not much at all!
I would like to be able to split like so:
name: jo mamma
location: Atlanta, Georgia
description: He is a good boy, and he is pretty funny
skills: not much at all!
I have tried using the explode function and the regex preg_split.
$exploded = explode(",", $data);
$regex = preg_split("/,\s/", $data);
But not getting the intended results because its splitting also after boy, and after Georgia. Results below:
name: jo mamma
location: Atlanta
Georgia
description: He is a good boy
and he is pretty funny
skills: not much at all!
Any help would be greatly appreciated. Thanks.
Just do this simple split using Zero-Width Positive Lookahead . (It will split by only , after which there is text like name:).
$regex = preg_split("/,\s*(?=\w+\:)/", $data);
/*
Array
(
[0] => "name: jo mamma"
[1] => "location: Atlanta, Georgia"
[2] => "description: He is a good boy, and he is pretty funny"
[3] => "skills: not much at all!"
)
*/
Learn more on lookahead and lookbehind from here : http://www.regular-expressions.info/lookaround.html
Use this regex:
name:\s(.*),\slocation:\s(.*),\sdescription:\s(.*),\sskills:\s(.*)
$text = 'name: jo mamma, location: Atlanta, Georgia, description: He is a good boy, and he is pretty funny, skills: not much at all!';
preg_match_all('/name:\s(.*),\slocation:\s(.*),\sdescription:\s(.*),\sskills:\s(.*)/', $text, $text_matches);
for ($index = 1; $index < count($text_matches); $index++) {
echo $text_matches[$index][0].'<br />';
}
Output:
jo mamma
Atlanta, Georgia
He is a good boy, and he is pretty funny
not much at all!
Regex101

Regex Pattern to fetch the text between the tags

my string is:
$p['message'] = '[name]Fozia Faizan[/name]\n[cell]03334567897[/cell]\n[city]Karachi, Pakistan[/city]';
What I want to do is to use REGEX pattern so as to get the result like this:
Name: Fozia Faizan
Cell #: 03334567897
City: Karachi, Pakistan
I've tried this regex:
$regex = "/\\[(.*?)\\](.*?)\\[\\/\\1\\]/";
$message = preg_match_all($regex, $p['message'], $matches);
but it didn't work at all. Please help
Well, using the great reply from #jh314, you could write:
$p['message'] = '[name]Fozia Faizan[/name]\n[cell]03334567897[/cell]\n[city]Karachi, Pakistan[/city]';
$m = array();
preg_match_all('|\[(.*?)](.*?)\[/\1]|', $p['message'], $m);
$result = #array_combine($m[1], $m[2]);
$out = "Name: {$result['name']}\nCell #: {$result['cell']}\nCity: {$result['city']}";
echo $out;
//$outHTML = nl2br("Name: {$result['name']}\nCell #: {$result['cell']}\nCity: {$result['city']}");
//echo $outHTML;
That will give you:
Name: Fozia Faizan
Cell #: 03334567897
City: Karachi, Pakistan
EDIT: You could also add # just before the name of the function like so: #array_combine, to suppress error at top of your page, only if this does work and you get the results as expected.
Your regex already works, just combine the result in $matches:
$p['message'] = '[name]Fozia Faizan[/name]\n[cell]03334567897[/cell]\n[city]Karachi, Pakistan[/city]';
$regex = "/\\[(.*?)\\](.*?)\\[\\/\\1\\]/";
preg_match_all('~\[(.*?)](.*?)\[/\1]~', $p['message'], $matches);
$result = array_combine ($matches[1], $matches[2]);
print_r($result);
will give you:
Array
(
[name] => Fozia Faizan
[cell] => 03334567897
[city] => Karachi, Pakistan
)

new lines for text box in php

I am having one HTML form, where in the address to be entered in text box
and the PHP out produce the data with following php code as:
$address = $_POST["address"];
echo $address;
And the out put comes in a single line like:
The Manager, Scotia bank Ltd,Cincinnati Finance Center,26 W. Martin Luther King Road, Cincinnati, Ohio 45268
But I need the out put in readable manner in 3-4 lines.
i.e for each "," break / new line to be made - so that the out put would be:
The Manager,
Scotia bank Ltd,
Cincinnati Finance Center,
26 W. Martin Luther King Raod,
Cincinnati,
Ohio 45268
Can any body help me getting the soluation please?
If the output is displayed in a textarea:
$address = str_replace(",",",\n",$_POST['address']);
echo $address;
If its on HTML:
$address = str_replace(",",",<br/>",$_POST['address']);
echo $address;
If , is the delimiter that you want to split the string then try with explode in php
$str = 'The Manager, Scotia bank Ltd,Cincinnati Finance Center,26 W. Martin Luther King Road, Cincinnati, Ohio 45268';
$arr = explode(',',$str);
print_r($arr);
Check the manual for more
Explode is the function you are searching for..
$str = 'The string';
$arr = explode(',',$str);
print_r($arr);
Learn more about explode here.
Perhaps something like:
implode(",\n", explode(",", $string));
You can use explode.Try this :
<?php
$str= "The Manager, Scotia bank Ltd,Cincinnati Finance Center,26 W. Martin Luther King Road, Cincinnati, Ohio 45268";
$arr = explode(",",$str);
for($i=0;$i<count($arr);$i++)
{
if($i==(count($arr)-1))
$comma = "";
else
$comma = ",";
echo $arr[$i].$comma."<br>";
}

Breaking a given HTML code using Reg Exp

Can anyone help me with a quick regex problem?
I have the following HTML:
555 Some Street Name<BR />
New Providence VA 22901-1311<BR />
United States<BR />
The first row is always the Street
Second row is City (which can have spaces) space State Abbv. space Zip hyphen 4 digit zip
Third row is the Country.
I need to break the HTML into a variable each. Can anyone provide a quick regex?
Edit: Maybe I wasn't clear. I need the following:
Street address, City, State, Zip, 4Digit Zip, Country as individual variables.
This doesn't even require regular expressions. You can split the diefferent lines using explode("<BR />",...). First line is Street, Last line is country. The middle line can be split using substr(), as you know that the last 4 characters are the 4 digit ZIP, the 6 characters before them are the ZIP followed by a hyphen and the 3 characters before them are the state followed by a space. So the numbers of characters of the segments (counted from the end of the line) is constant.
555 Some Street Name<BR />
New Providence VA 22901-1311<BR />
United States<BR />
ok, for the first part, let's split the lines
$array = explode('<BR />', $address);
now you need to get the informations from the second line to be parsed as well...
$array[1] = New Providence VA 22901-1311;
$tmp = explode(' ', $array[1]);
and all you need now is to set everything in the correct variable names
$fullZip = array_pop($tmp);
$zipArray = explode('-',$fullZip);
$zip = $zipArray[0];
$Digitzip = $zipArray[1];
$state = array_pop($tmp);
$providence = implode($tmp);
$country = $array[2];
$street = $array[0];
$array = explode('<BR />', $address);
This is the easiest way, just split the string by the <br />-tags. If you can avoid regular expressions, you should do, cause they are not as performant than simple string operations like an explode.
No need for a regex.
$htmlStr = '555 Some Street Name<BR />New Providence VA 22901-1311<BR />United States<BR />';
Live example
Note, however, that for more complicated HTML parsing, regexes are not the tool for the job.

Categories