How to match 2 unknown letters after a letter in php - php

i am trying to get this
string = 'Boss S02E06 more string'
i want S02E06 out of the complete string . and if possible split the string there.
Please note that the values after S and E in that keep changing so its not constant .
But im not expert when it comes to it.But i guess its time to start learning.
Thanks guys

try this:
$string = "Boss S02E06 more string";
preg_match(`.*(S\d+E\d+).*`,$string,$match);
echo $match[0];// it will echo S02E06

You would use a Regular Expression. You can learn them here.
PHP has preg_match(), which is what you would use.
The regex to match would be something like S\d+E\d+. If you want the values, use a capturing group.
It's up to you to put all these ideas together to arrive at an answer.

Related

Extract value from between quotes with regex

I have the following string:
feature name="osp"
I need to extract part of the strings out and put them into a new string. The word feature can change and the word inside quotes can change so I need to be able to capture any instance possible. The name=" " part is always the same. The result I need is:
feature osp
I need to filter out the name= and quotes from the string.
I've used this ^\w*\s to get the first feature part but can't figure out how to extract osp from the string using a regex. I've been looking here RegEx: Grabbing values between quotation marks but can't get a regex that combines both to get the result I need. I'm working in PHP so using preg-match at the moment. Can anyone help with this?
I'd go with
(\w+)\s+name\s*=\s*"([^"]*)
It's a little bit slower, but it allows for arbitrary number of spaces and it captures the first word correctly, even with Alexandru's test.
See it work here at regex101.
Regards
Try something like that:
preg_match('/(.+)name="(.+?)"/', $string, $matches);
echo $matches[1] . $matches[2];
An improved version of #vuryss
preg_match('/(.*?)name="(.*?)"/ims', $string, $matches);
echo $matches[1] . $matches[2];

Get specific string content inside big string

I have a big string like this:
[/az_column_text][/vc_column_inner][vc_column_inner width="3/4"]
[az_latest_posts post_layout="listed-layout" post_columns_count="2clm" post_categories="assemblea-soci-2015"]
[/vc_column_inner][/vc_row_inner][/vc_column]
What I need to extract:
assemblea-soci-2015
Of course this value can change, and also the big string can change too. I need a regex or something else to extract this value (it will be always from post_categories="my-value-to-extract") from this big string.
I think to take post_categories=" as the beginning of a possible substring and the next char " as the end of my portion, but no idea how to do this.
Is there an elegant way to do this also for future values with, of course, different length?
You can use this regex in PHP:
post_categories="\K[^"]+
RegEx Demo
You can use this regex:
(?<=post_categories=")[^"]+(?=")
?<= (lookbehind) looks for post_categories=" before the desired match, and (?=) (lookahead) looks for " after the desired match.
[^"] gets the match (which is assumed not to contain any ")
Demo
Example PHP code:
$text='[/az_column_text][/vc_column_inner][vc_column_inner width="3/4"]
[az_latest_posts post_layout="listed-layout" post_columns_count="2clm" post_categories="assemblea-soci-2015"]
[/vc_column_inner][/vc_row_inner][/vc_column]';
preg_match ("/(?<=post_categories=\")[^\"]+(?=\")/", $text,$matches);
echo $matches[0];
Output:
assemblea-soci-2015
This should extract what you want.
preg_match ("/post_categories=\"(.*)\"\[\]/", $text_you_want_to_use)

php regexp "AND"

I have to create translations for the project I work on. The simplest solution was to change all stings to a functioncall(string) so that I could get unique string hashes everytime.
My code has the following different t() function uses:
<label for="anon"><?php echo t('anonymously? (20% extra)')?></label>
exit(t("Success! You made {amount} oranges out of it!", array('amount' => $oranges)));
echo t('You failed.');
My current regexp is:
$transMatches = preg_match_all('/[^a-z]t\([^)(]+/m', $contents, $matches);
The problem is that it fails on #1 example, matchin "anonymously?".
What I really want to achieve is: "match t( then match either ' or " then match anything except what you matched for ' or " and )"
Idea: t\(['|"](.*?)[^'|"]\)?
I cannot make above regexp to work.
How could I do AND in regexp so that it matches "['|"] AND )" OR "['|"] AND, array"
Please help me on regexp and explain why it works.
Thank you!
Parsing function arguments may be quite complex, but you need to parse only the first argument which (for simplicity) can assume always to be string escaped either with ' or with ", thus those regexps may match"
"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"
\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*'
Therefore you just need to match:
'~[^\w\d]t\(\s*("[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\')~i'
[^\w\d] assumes that no test1t will match, \s* makes you space tolerant...
With this regexp you'll get results like:
'anonymously? (20% extra)'
"Success! You made {amount} oranges out of it!"
And I can't imagine situation where you would need to parse out array too, can you describe it in comment/question?
Is this what you need?
Using Backreferences in The Regular Expression - http://www.regular-expressions.info/brackets.html
But it looks strange what are you doing, and why?
Are you replacing the function call with some result? why dont you just let it call the function and return translation from it?

php preg_replace - replace part of social

I want to find any pattern matching: ###-##-####
and replace the ###-##, with ***-**
but leave the -####
I tried this below, but nothing is being replaced at all.
preg_replace('/(^[\d]{3})(-)([\d]{2})(-[\d]{4}$)/','\2\4',$myText);
Any help is appreciated
Update, here is my entire code string as it currently stands, after trying a few of the suggestions below. I am comparing the second echo output to the first... and the social numbers all remain the same.
Also, as it was mentioned below, my string does contain more than just a social... it is thousands of characters long. which i think is my real issue. Sorry if i didnt clear that up in the beginning.
//Make the CSC credit report request.
$strCscResponse = $Csc->makeRequest($strFixedFormatRecord);
echo "<br/><br/><pre>" . $strCscResponse . "</pre><br/><br/>";
$strCscResponse = str_replace("!", " ", $strCscResponse);
$strCscResponse = preg_replace('/^\d{3}-\d{2}(-\d{4})$/','***-**$1',$strCscResponse);
echo "<br/><br/><pre>" . $strCscResponse . "</pre><br/><br/>";
update
I'd like to mark all the answers and "the answer" just because i didnt clarify the string has more than just a social in it. thank you for the help with this issue, embarrisingly enough it has been driving me wild for a couple days now.
There is one possible problem: you might not be matching the right string (if you are trying to find SSNs buried in a large block of text) - the ^ and $ anchors will only match beginning of string (or sometimes beginning of line) - if this is not what you want, but instead you want to find SSNs in a long string, you need to get rid of those anchors.
The other problem, potentially, is that you seem to want to replace things with asterisks, but you do not include asterisks in your replacement expression. you need to use a replacement expression like
`***-**\4`
Try this regex:
(\d{3})(-)(\d{2})(-\d{4})
Try this:
preg_replace('/^\d{3}-\d{2}(-\d{4})$/','***-**$1',$myText);
you have ^ and $ in your pattern, but I see no m modifier, so this
will only match if ###-##-#### is the entire string.
[\d] can be
shortened to \d
your \2\4 will leave --####, if you wanted *-####
you can simply have *\4

Replacing a string inside a string in PHP

I have strings in my application that users can send via a form, and they can optionally replace words in that string with replacements that they also specify. For example if one of my users entered this string:
I am a user string and I need to be parsed.
And chose to replace and with foo the resulting string should be:
I am a user string foo I need to be parsed.
I need to somehow find the starting position of what they want to replace, replace it with the word they want and then tie it all together.
Could anyone write this up or at least provide an algorithm? My PHP skills aren't really up to the task :(
Thanks. :)
$result = preg_replace('/\band\b/i', 'foo', $subject);
will find all occurences of and where it's a word on its own and replace it with foo. \b ensures that there is a word boundary before and after and.
use preg_replace. You don't need to think so hard about this though you will have to learn a little bit about regexes. :)
Read up on str_replace, or for more complex replacements on Regular Expressions and preg_replace.
Examples for both:
<?php
$str = 'I am a user string and I need to be parsed.';
echo str_replace( 'and', 'foo', $str ) . "\n";
echo preg_replace( '/and/', 'foo', $str ) . "\n";
?>
In response to the comments of this answer, note that both examples above will replace every occurrence of the search string (and), even when it happens to be within another word.
To take care of that you either have to add the word separators to the str_replace call (see the comment of an example), but this will get quite complicated when you want to take care of all common word separators (space, commas, dots, exclamation marks, question marks etc.).
An easier to way to fix this problem is to use the power of regular expressions and make sure, the actual search string is not found within another word. See Tim Pietzcker's example below for a possible solution.

Categories