PHP -- need to explode a string with 2 different delimiters - php

I've got a string $newstring loaded with lines that look like:
<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009 <br>
I want to explode $newstring using <tt> and <br> as the delimiters.
How can I use preg_split() or anything else to explode it?

Alright I'm on my Nexus 7, and I've found it isn't too elegant to answer questions on a tablet, but regardless you can do this using preg_split using the following regex:
<\/?tt>|</?br>
See the regex working here: http://www.regex101.com/r/kX0gE7
PHP code:
$str = '<tt>Thu 01-Mar-2012</tt>  7th of Atrex, 3009<br>';
$split = preg_split('#<\/?tt>|</?br>#', $str);
var_export($split);
The array $split will contain:
array (
0 => '',
1 => 'Thu 01-Mar-2012',
2 => ' 7th of Atrex, 3009',
3 => ''
)
(See http://ideone.com/aiTi5U)

You should try this code..
<?php
$keywords = preg_split("/\<tt\>|\<br\>/", "<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009 <br>");
print_r($keywords);
?>
Look at the CodePad exapmle.
IF you want to include </tt> also then use.. <\/?tt>|<br>. See Example.

try this code..
<?php
$newstring = "<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br>";
$newstring = (explode("<tt>",$newstring));
//$newstring[1] store Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br> so do opration on that.
$newstring = (explode("<br>",$newstring[1]));
echo $newstring[0];
?>
output:-->
Thu 01-Mar-2012</tt> 7th of Atrex, 3009

If the <tt> and <br/> tags are the only tags in the string, a simple regex like this will do:
$exploded = preg_split('/\<[^>]+\>/',$newstring, PREG_SPLIT_NO_EMPTY);
The expression:
delimiters start and end with < and > respectively
In between these chars at least 1 [^>] is expected (this is any char except for the closing >
PREG_SPLIT_NO_EMPTY
This is a constant, passed to the preg_split function that avoids array values that are empty strings:
$newString = '<tt>Foo<br/><br/>Bar</tt>';
$exploded = preg_split('/\<[^>]+\>/',$newstring);
//output: array('','Foo','','Bar',''); or something (off the top of my head)
$exploded = preg_split('/\<[^>]+\>/',$newstring, PREG_SPLIT_NO_EMPTY);
//output: array('Foo', 'Bar')
If, however, you're dealing with more than these two tags, or variable input (as in user-supplied), you might be better off parsing the markup. Look into php's DOMDocument class, see the docs here.
PS: to see the actual output, try echo '<pre>'; var_dump($exploded); echo '</pre>';

function multiExplode($delimiters,$string) {
return explode($delimiters[0],strtr($string,array_combine(array_slice($delimiters,1),array_fill(0,count($delimiters)-1,array_shift($delimiters)))));
}
EX: $values = multiExplode(array("",""),$your_string);

Here is a custom function with example.
http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/

Related

How to use explode and get first element in one line in PHP?

$beforeDot = explode(".", $string)[0];
This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.
The function array dereferencing was implemented in PHP 5.4, so if you are using an older version you'll have to do it another way.
Here's a simple way to do it:
$beforeDot = array_shift(explode('.', $string));
You can use list for this:
list($first) = explode(".", "foo.bar");
echo $first; // foo
This also works if you need the second (or third, etc.) element:
list($_, $second) = explode(".", "foo.bar");
echo $second; // bar
But that can get pretty clumsy.
Use current(), to get first position after explode:
$beforeDot = current(explode(".", $string));
Use array_shift() for this purpose :
$beforeDot = array_shift(explode(".", $string));
in php <= 5.3 you need to use
$beforeDot = explode(".", $string);
$beforeDot = $beforeDot[0];
2020 : Google brought me here for something similar.
Pairing 'explode' with 'implode' to populate a variable.
explode -> break the string into an array at the separator
implode -> get a string from that first array element into a variable
$str = "ABC.66778899";
$first = implode(explode('.', $str, -1));
Will give you 'ABC' as a string.
Adjust the limit argument in explode as per your string characteristics.
You can use the limit parameter in the explode function
explode($separator, $str, $limit)
$txt = 'the quick brown fox';
$explode = explode(' ', $txt, -substr_count($txt, ' '));
This will return an array with only one index that has the first word which is "the"
PHP Explode docs
Explanation:
If the limit parameter is negative, all components except the last
-limit are returned.
So to get only the first element despite the number of occurences of the substr you use -substr_count

How to get part of string from the end in PHP?

I am making application where I receive a string from user. The string is concatenated with - character between them. First part of string contains alphabetic data whereas later part contains integers or floating point numbers. For example: A string might be 3 Cups Tea-5.99.I want to get the later part of string 5.99 separated by - character. How to do that? I know about PHP substr() function but that takes fixed characters to retrieve substring from. But in this case the later part will not be fixed. For example: 2 Jeans-65.99. In this case I would need last 4 characters meaning that I can't use substr() function.
Anybody with solution?
I know I would need to apply regex but I am completely novice in Regex.
Waiting for your help.
Thanks!
Simply
$result = explode('-', $string)[1];
For PHP<5.4 you'll have to use temporary variable:
$data = explode('-', $string);
$result = $data[1];
Edit
As mentioned in comments, if there is more than 1 part, that will be:
$result = array_pop(explode('-', $string));
$bits = explode('-', $inputstring);
echo $bits[1];
You can use substr() with strpos():
$str = '3 Cups Tea-5.99';
echo substr($str, strpos($str, "-") + 1);
Output:
5.99
Demo!
If data will be like this: "1-Cup tea-2.99", then
$data = "1-Cup tea-2.99";
$data = explode('-', $string);
$result = $data[count($data)-1];

php regex how to remove duplicate strings

here is a long string like"abc,adbc,abcf,abc,adbc,abcf"
I want to use regex to remove the duplicate strings which are seperated by comma
the following is my codes, but the result is not what I expect.
$a='abc,adbc,abcf,abc,adbc,abcf';
$b=preg_replace('/(,[^,]+,)(?=.*?\1)/',',',','.$a.',');
echo $b;
output:,adbc,abc,adbc,abcf,
It should be : ,abc,adbc,abcf,
please point my problem. thanks.
Here I am sharing simple php logic instead regex
$a='abc,adbc,abcf,abc,adbc,abcf';
$pieces = explode(",", $a);
$unique_values = array_unique($pieces);
$string = implode(",", $unique_values);
Here is positive lookahead base attempt on regex based solution to OP's problem.
$arr = array('ball ball code', 'abcabc bde bde', 'awycodeawy');
foreach($arr as $str)
echo "'$str' => '" . preg_replace('/(\w{2,})(?=.*?\\1)\W*/', '', $str) ."'\n";
OUTPUT
'ball ball code' => 'ball code'
'abcabc bde bde' => 'abc bde'
'awycodeawy' => 'codeawy'
As you can for the input 'awycodeawy' it makes it to 'codeawy' instead of 'awycode'. The reason is that it is possible to find a variable length lookahead something which is not possible for lookbehind.
You can also try
echo implode(",", array_unique(preg_split(",", $yourLongString)));
Try this....
$string='abc,adbc,abcf,abc,adbc,abcf';
$exp = explode(",", $string);
$arr = array_unique($exp);
$output=implode(',', $arr);

A bit lost with preg_match regular expression

I'm a beginner in regular expression so it didn't take long for me to get totally lost :]
What I need to do:
I've got a string of values 'a:b,a2:b2,a3:b3,a4:b4' where I need to search for a specific pair of values (ie: a2:b2) by the second value of the pair given (b2) and get the first value of the pair as an output (a2).
All characters are allowed (except ',' which seperates each pair of values) and any of the second values (b,b2,b3,b4) is unique (cant be present more than once in the string)
Let me show a better example as the previous may not be clear:
This is a string: 2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,never:0
Searched pattern is: 5
I thought, the best way was to use function called preg_match with subpattern feature.
So I tried the following:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$re = '/(?P<name>\w+):5$/';
preg_match($re, $str, $matches);
echo $matches['name'];
Wanted output was '5 minutes' but it didn't work.
I would also like to stick with Perl-Compatible reg. expressions as the code above is included in a PHP script.
Can anyone help me out? I'm getting a little bit desperate now, as Ive spent on this most of the day by now ...
Thanks to all of you guys.
$str = '2 minutes:2,51 seconds:51,5 minutes:5,10 minutes:10,15 minutes:51,never:0';
$search = 5;
preg_match("~([^,\:]+?)\:".preg_quote($search)."(?:,|$)~", $str, $m);
echo '<pre>'; print_r($m); echo '</pre>';
Output:
Array
(
[0] => 5 minutes:5
[1] => 5 minutes
)
$re = '/(?:^|,)(?P<name>[^:]*):5(?:,|$)/';
Besides the problem of your expression having to match $ after 5, which would only work if 5 were the last element, you also want to make sure that after 5 either nothing comes or another pair comes; that before the first element of the pair comes either another element or the beginning of the string, and you want to match more than \w in the first element of the pair.
A preg_match call will be shorter for certain, but I think I wouldn't bother with regular expressions, and instead just use string and array manipulations.
$pairstring = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
function match_pair($searchval, $pairstring) {
$pairs = explode(",", $str);
foreach ($pairs as $pair) {
$each = explode(":", $pair);
if ($each[1] == $searchval) {
echo $each[0];
}
}
}
// Call as:
match_pair(5, $pairstring);
Almost the same as #Michael's. It doesn't search for an element but constructs an array of the string. You say that values are unique so they are used as keys in my array:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$a = array();
foreach(explode(',', $str) as $elem){
list($key, $val) = explode(':', $elem);
$a[$val] = $key;
}
Then accessing an element is very simple:
echo $a[5];

regex split string at first line break

I would like to split a string at the first line break, instead of the first blank line
'/^(.*?)\r?\n\r?\n(.*)/s' (first blank line)
So for instance, if I have:
$str = '2099 test\nAre you sure you
want to continue\n some other string
here...';
match[1] = '2099 test'
match[2] = 'Are you sure you want to continue\n some other string here...'
preg_split() has a limit parameter you can take to your advantage. You could just simply do:
$lines = preg_split('/\r\n|\r|\n/', $str, 2);
<?php
$str = "2099 test\nAre you sure you want to continue\n some other string here...";
$match = explode("\n",$str, 2);
print_r($match);
?>
returns
Array
(
[0] => 2099 test
[1] => Are you sure you want to continue
some other string here...
)
explode's last parameter is the number of elements you want to split the string into.
Normally just remove on \r?\n:
'/^(.*?)\r?\n(.*)/s'
You can use preg_split as:
$arr = preg_split("/\r?\n/",$str,2);
See it on Ideone
First line break:
$match = preg_split('/\R/', $str, 2);
First blank line:
$match = preg_split('/\R\R/', $str, 2);
Handles all the various ways of doing line breaks.
Also there was a question about splitting on the 2nd line break. Here is my implementation (maybe not most efficient... also note it replaces some line breaks with PHP_EOL)
function split_at_nth_line_break($str, $n = 1) {
$match = preg_split('/\R/', $str, $n+1);
if (count($match) === $n+1) {
$rest = array_pop($match);
}
$match = array(implode(PHP_EOL, $match));
if (isset($rest)) {
$match[] = $rest;
}
return $match;
}
$match = split_at_nth_line_break($str, 2);
Maybe you don't even need to use regex's. To get just split lines, see:
What's the simplest way to return the first line of a multi-line string in Perl?

Categories