i'm new to regular expressions and would like to match the first and last occurrences of a term in php. for instance in this line:
"charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie"
i would like to just access the first and last "charlie", but not the two in the middle. how would i just match on the first and last occurrence of a term?
thanks
If you know what substring you're looking for (ie. it's not a regex pattern), and you're just looking for the positions of your substrings, you could just simply use these:
strpos — Find position of first occurrence of a string
strrpos — Find position of last occurrence of a char in a string
Try this regular expression:
^(\w+),.*\1
The greedy * quantifier will take care that the string between the first word (\w+) and another occurrence of that word (\1, match of the first grouping) is as large as possible.
You need to add ^ and $ symbols to your regular expression.
^ - matches start of the string
$ - matches end of the string
In your case it will be ^charlie to match first sample and charlie$ to match last sample. Or if you want to match both then it will be ^charlie|charlie$.
See also Start of String and End of String Anchors for more details about these symbols.
Try exploding the string.
$names = "charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie";
$names_array = explode(",", $names);
After doing this, you've got an array with the names. You want the last, so it will be at position 0.
$first = $names_array[0];
It gets a little trickier with the last. You have to know how many names you have [count()] and then, since the array starts counting from 0, you'll have to substract one.
$last = $names_array[count($names_array)-1];
I know it may not be the best answer possible, nor the most effective, but I think it's how you really start getting programming, by solving smaller problems.
Good luck.
Related
Using a regular expression I want to move two letters in a string.
W28
L36
W29-L32
Should be changed to:
28W
36L
29W-32L
The numbers vary between 25 and 44. The letters that need to be moved are always "W" and/or "L" and the "W" is always first when they both exist in the string.
I need to do this with a single regular expression using PHP. Any ideas would be awesome!
EDIT:
I'm new to regular expressions and tried a lot of things without success. The closest I came was using "/\b(W34)\b/" for each possibility. I also found something about using variables in the replace function but had no luck using these.
Your regex \b(W34)\b matches exactly W34 as a whole word. You need a character class to match W or L, and some alternatives to match the numeric range, and use the most of capturing groups.
You can use the following regex replacement:
$re = '/\b([WL])(2[5-9]|3[0-9]|4[0-4])\b/';
$str = "W28\nL36\nW29-L32";
$result = preg_replace($re, "$2$1", $str);
echo $result;
See IDEONE demo
Here, ([WL]) matches and captures either W or L into group 1, and (2[5-9]|3[0-9]|4[0-4]) matches integer numbers from 25 till 44 and captures into group 2. Backreferences are used to reverse the order of the groups in the replacement string.
And here is a regex demo in case you want to adjust it later.
i want to preg_match following as it is
$this_string = '{95}1340{113}1488{116}1545{99}1364';
My best try was
preg_match('/^[\{\d+\}\d+]+$/', $this_string);
That matches
{95}1340{113}1488
but also
{95}1340{113}
which is wrong.
I know why it is matching last example. One match {95}1340 was true, so '+' 'll be always true. But i don't know how to tell, if it match, so it has always be a complete match in '[…]'
i do expect only matches likes these
{…}…
{…}…{…}…
{…}…{…}…{…}…
one of the tries:
^(\{\d+\}\d+)+$
does also match
{99}1364
at the very last end of this string as a second match, so i get back an Array with two Elements:
Array[0] = {95}1340{113}1488{116}1545{99}1364 and
Array[1] = {99}1364
Problem is unnecessary use of character class in your regex i.e. [ and ].
You can use:
'/^(\{\d+\}\d+)+$/'
The translation of your regex to a clearer thing would be: /^[\{\}0-9+]+$/, this would be explained as everything that is inside this chracters {}0123456789+, exactly those ones.
What you want is grouping, for grouping, parentheses are needed and not character classes () instead [], so what you want to do is replace [] for ().
Short answer: '/^(\{\d+\}\d+)+$/'
What you are trying to do is a little unclear. Since your last edit, I assume that you want to check the global format of the string and to extract all items (i.e. {121}1231) one by one. To do that you can use this code:
$str = '{95}1340{113}1488{116}1545{99}1364';
$pattern = '~\G(?:{\d+}\d+|\z)~';
if (preg_match_all($pattern, $str, $matches) && empty(array_pop($matches[0])))
print_r($matches[0]);
\G is an anchor for the start of the string or the end of the previous match
\z is an anchor for the end of the string
The alternation with \z is only needed to check that the last match is at the end of the string. If the last match is empty, you are sure that the format is correct until the end.
I am curling an page and getting the output
however what is happening is that the html encoding is being removed so new lines are being skipped,
so it looks like this
This is Bob. He lives in an boatBut he only has one oar to row with.
in order to detect new lines I figure it was easier to just check for strings that only have One upper case letter and spaces inbetween, so far I have this
(\s\w+\s\w+.\s\D+[a-z][A-Z])
However this does not seem to work
as it only matches this
is Bob. He lives in an boatB
see here http://regex101.com/r/gH0lW1
how to match all strings that have spaces and match all strings up to one Uppercase letter
Update: this will split on the condition without losing any characters
<?php
$string = "This is Bob. He lives in an boatBut he only has one oar to row with.He also does stuff, it is cool.";
$array = preg_split('/(?<=[a-z.])(?=[A-Z])/', $string);
print_r($array);
?>
Use a positive lookbehind to ensure you capture a capital after a lowercase:
(?<=[a-z])[A-Z]
http://regex101.com/r/cB7bD8
You could use php's preg_split if you want, to explode the result on this regex.
(.*?(?:\w+(?=[A-Z]))|\1)
This regex has a recursive part that will match more than 1 sentence in a whole text. So you can check the Live demo and see the matched groups.
But,
If you wanna include a newline on each sentence begins after a period (.) as well, then I modify above regex to this:
(.*?(?:(?:\w+|\. *)(?=[A-Z]))|\1)
and now you can compare results with the first regex HERE
I have some php string like below
abc-1987-mp3-songs
xyz-1999-india-mp3-songs
dec-2001-mp3-songs
ryu-2012-freemp3-songs
Now I want these string splited at last found numeric values like below
abc-1987
xyz-1999
dec-2001
ryu-2012
Please help me that which regex can be used to do this. thanks.
Ok, I had a look (do take some time to learn regex - but meanwhile):
$split = (preg_split('/(^.*?[0-9]+)\-?[^0-9]+/', 'foo-xyz-1999-india-mp3-songs', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
echo $split[0];//<--- foo-xyz-1999, just like you wanted
Dumps an array with foo-xyz-1999 as first value, which is what you need. If you want to know what every part of the regex does read it here
The only difference is that, though the whole string becomes its own delimiter, there are two delimiters (the first part, always ending on a series of numbers and the rest of the string, that doesn't contain any more digits)
Use explode insted of regular expression
for example:-
$str="abc-1987-mp3-songs";
$f=explode("-",$str);
echo $final_result=$f[0]."-".$f[1];
or if you want to use reg exp.then
<?php
$str="abc-1987-mp3-songs";
echo $f=preg_replace('/[^0-9]/','', $str);
?>
Above code give you all the numeric digits of your string.
This would match last occurrence of numeric value from given string:
([\w\d-]*-[\d]+)
This is the link: Regex
I'm not sure where to start with this one but I'm hoping someone can help.
When a user submits a message I want to check the string and return the first letter of each sentence and place it into an array. Basically I want the first letter in the string and every letter immediately after a full stop (if there are any) placed in an array.
Has anyone ever done this in the past? Is it even possible?
Hoping you can help
Cj
Split the string in sentences - use explode() or preg_split() with the punctiation mark. Then loop all sentences an get the first letter using mb_substr($sentence, 0, 1); Don't forget to trim all senteces from whitespaces at the start or end of sentence.
You could use a regex like:
preg_match_all("/\b\w/", $yourString, $matches);
And then $matches will contain an array with an entry for every one of the characters your are looking for.