I have strings like this
[Ljava.lang.String;
[Ldummy.class.Here;
[Lanother.unknown.Class;
What regex should i use to replace [L and ; with <span>,[]</span>
And make it look like this
<span>java.lang.String[]</span>
<span>dummy.class.Here[]</span>
<span>another.unknown.Class[]</span>
What i want is to make java array class string representation more human friendly
I've heard about $1 or something like that, but i couldn't find more information as i don't know what is it
$strings = "[Ljava.lang.String;
[Ldummy.class.Here;
[Lanother.unknown.Class;";
$strings = preg_replace('/\[L([A-Za-z\.]+);/', '<span>$1[]</span>', $strings);
echo $strings;
Output:
$ php foo.php
<span>java.lang.String[]</span>
<span>dummy.class.Here[]</span>
<span>another.unknown.Class[]</span>
If you want to use plain old PHP for this rather than a regex, here is a simple snippet that will do exactly what you need - and you can modify it without having to sort through regex that makes little sense to you:
<?php
$stringArray=array(
'[Ljava.lang.String;',
'[Ldummy.class.Here;',
'[Lanother.unknown.Class;'
);
foreach($stringArray as $val)
{
$output=$val;
if($val[0].$val[1]=='[L')
{
$output="<span>".substr($val,2);
}
if(substr($output,-1)==';')
{
$output=substr($output,0,strlen($output)-1).'</span>';
}
echo $output.'<br>';
}
?>
Output:
<span>java.lang.String</span>
<span>dummy.class.Here</span>
<span>another.unknown.Class</span>
This should do it:
$new_content = preg_replace('#^\[L(.*);\s*$#m', '<span>$1[]</span>', $content);
Demo here: http://sandbox.onlinephpfunctions.com/code/8f0de08b5ba0882db2d98d99cdd961b9aebab074
You can use this:
$result = preg_replace('~\[L([^;]+);~', '<span>$1[]</span>', $txt);
where [^;]+ matches all that is not a ";"
Related
I have a array that looks like this:
[cspacer231]
[*spacer231]
[*spacer10]-
[*spacer2]
[*spacer3210]-
[cspacer2221]
Now, I want to take all [*spacerNUMBER] without the - at the end.
My try was this "/\[\*spacer(.*?)](?!-)/", but it just takes the first child.
Any help will be appreciated.
Try the following:
"/\[\*spacer(.*?)\]$/"
The $ sign requires that there's nothing after ].
If you want to restrict to numbers after spacer:
"/\[\*spacer([0-9]*?)\]$/"
try with:
/\[.*spacer(.*?)](?!-)/g
Your regex should be
\[\*spacer(\d+)\](?!-)
Demo: https://regex101.com/r/wD5fM9/1
used in PHP:
$array = array('[cspacer231]',
'[*spacer231]',
'[*spacer10]-',
'[*spacer2]',
'[*spacer3210]-',
'[cspacer2221]');
foreach($array as $thing) {
if(preg_match('~\[\*spacer(\d+)\](?!-)~', $thing, $match)) {
echo $match[1] . "\n";
}
}
Output:
231
2
You should use the \d+ so you are sure it is a number and not just anything.
I have a string http://localhost:9000/category that I want to replace with category.html, i.e. strip everything before /category and add .html.
But can't find a way to do this with str_replace.
You want to use parse_url in this case:
$parts = parse_url($url);
$file = $parts['path'].'.html';
Or something along that line. Experiment a bit with it.
Ismael Miguel suggested this shorter version, and I like it:
$file = parse_url($url,PHP_URL_PATH).'.html';
Much better than a ^*!$(\*)+ regular expression.
.*\/(\S+)
Try this.Replace by $1.html.see demo .
http://regex101.com/r/nA6hN9/43
Use preg_replace instead of str_replace
Regex:
.*\/(.+)
Replacement string:
$1.html
DEMO
$input = "http://localhost:9000/category";
echo preg_replace("~.*/(.+)~", '$1.html', $input)
Output:
category.html
A solution without regex:
<?php
$url = 'http://localhost:9000/category';
echo #end(explode('/',$url)).'.html';
?>
This splits the string and gets the last part, and appends .html.
Note that this won't work if the input ends with / (e.g.: $url = 'http://localhost:9000/category/';)
Also note that this relies on non-standard behavior and can be easily changed, this was just made as a one-liner. You can make $parts=explode([...]); echo end($parts).'.html'; instead.
If the input ends with / occasionally, we can do like this, to avoid problems:
<?php
$url = 'http://localhost:9000/category/';
echo #end(explode('/',rtrim($url,'/'))).'.html';
?>
Having trouble with preg_match syntax
with in a page I need to find anything like
$first = '/>http:\/\/www.(.*?)\/(.*?)\</';
$second = '/="http:\/\/www.(.*?)\/(.*?)"/';
How could I combine the two?
Something like
$regex = '/(?="|>)http:\/\/www.(.*?)/(.*?)(?"|\<)/';
Sorry not very good at this.
This looks about right to me:
/(?:="|>)http:\/\/www\.(.*?)\/(.*?)["<]/i
Notice a few minor corrections: Your non-capturing group syntax was a little off (it should be (?:pattern) instead of (?pattern)), and you also needed to escape the . and /.
I'm also not sure the (.*?)\/(.*?) is doing exactly what you think it is; I'd probably just replace that with (.*?) unless you want to require a / character.
Here is a funny thought.
Use /(?:(=")|>)http:\/\/www\.(.*?)\/(.*?)(?(1)"|<)/sg using a looping find next search. Extracting variables $2 and $3 each time. This uses a conditional.
Or, use /(?|(?<==")http:\/\/www\.(.*?)\/(.*?)(?=")|(?<=>)http:\/\/www\.(.*?)\/(.*?)(?=<))/sg in a match all. This uses branch reset. The array will acumulate as pairs ($cnt++ % 2).
Depends on what you mean by combining.
A perl test case:
use strict;
use warnings;
my $str = '
<tag asdf="http://www.some.com/directory"/>
<dadr>http://www.adif.com/dir</dadr>
';
while ( $str =~ /(?:(=")|>)http:\/\/www\.(.*?)\/(.*?)(?(1)"|<)/sg )
{
print "'$2' '$3'\n";
}
print "--------------\n";
my #parts = $str =~ /(?|(?<==")http:\/\/www\.(.*?)\/(.*?)(?=")|(?<=>)http:\/\/www\.(.*?)\/(.*?)(?=<))/sg;
my $cnt = 0;
for (#parts)
{
print "'$_' ";
if ($cnt++ % 2) {
print "\n";
}
}
__END__
Output:
'some.com' 'directory'
'adif.com' 'dir'
--------------
'some.com' 'directory'
'adif.com' 'dir'
I have a really long string in a certain pattern such as:
userAccountName: abc userCompany: xyz userEmail: a#xyz.com userAddress1: userAddress2: userAddress3: userTown: ...
and so on. This pattern repeats.
I need to find a way to process this string so that I have the values of userAccountName:, userCompany:, etc. (i.e. preferably in an associative array or some such convenient format).
Is there an easy way to do this or will I have to write my own logic to split this string up into different parts?
Simple regular expressions like this userAccountName:\s*(\w+)\s+ can be used to capture matches and then use the captured matches to create a data structure.
If you can arrange for the data to be formatted as it is in a URL (ie, var=data&var2=data2) then you could use parse_str, which does almost exactly what you want, I think. Some mangling of your input data would do this in a straightforward manner.
You might have to use regex or your own logic.
Are you guaranteed that the string ": " does not appear anywhere within the values themselves? If so, you possibly could use implode to split the string into an array of alternating keys and values. You'd then have to walk through this array and format it the way you want. Here's a rough (probably inefficient) example I threw together quickly:
<?php
$keysAndValuesArray = implode(': ', $dataString);
$firstKeyName = 'userAccountName';
$associativeDataArray = array();
$currentIndex = -1;
$numItems = count($keysAndValuesArray);
for($i=0;$i<$numItems;i+=2) {
if($keysAndValuesArray[$i] == $firstKeyName) {
$associativeDataArray[] = array();
++$currentIndex;
}
$associativeDataArray[$currentIndex][$keysAndValuesArray[$i]] = $keysAndValuesArray[$i+1];
}
var_dump($associativeDataArray);
If you can write a regexp (for my example I'm considering there're no semicolons in values), you can parse it with preg_split or preg_match_all like this:
<?php
$raw_data = "userAccountName: abc userCompany: xyz";
$raw_data .= " userEmail: a#xyz.com userAddress1: userAddress2: ";
$data = array();
// /([^:]*\s+)?/ part works because the regexp is "greedy"
if (preg_match_all('/([a-z0-9_]+):\s+([^:]*\s+)?/i', $raw_data,
$items, PREG_SET_ORDER)) {
foreach ($items as $item) {
$data[$item[1]] = $item[2];
}
print_r($data);
}
?>
If that's not the case, please describe the grammar of your string in a bit more detail.
PCRE is included in PHP and can respond to your needs using regexp like:
if ($c=preg_match_all ("/userAccountName: (<userAccountName>\w+) userCompany: (<userCompany>\w+) userEmail: /", $txt, $matches))
{
$userAccountName = $matches['userAccountName'];
$userCompany = $matches['userCompany'];
// and so on...
}
the most difficult is to get the good regexp for your needs.
you can have a look at http://txt2re.com for some help
I think the solution closest to what I was looking for, I found at http://www.justin-cook.com/wp/2006/03/31/php-parse-a-string-between-two-strings/. I hope this proves useful to someone else. Thanks everyone for all the suggested solutions.
If i were you, i'll try to convert the strings in a json format with some regexp.
Then, simply use Json.
Would it be possible to make a regex that reads {variable} like <?php echo $variable ?> in PHP files?
Thanks
Remy
The PHP manual already provides a regular expression for variable names:
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
You just have to alter it to this:
\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\}
And you’re done.
Edit You should be aware that a simple sequential replacment of such occurrences as Ross proposed can cause some unwanted behavior when for example a substitution also contains such variables.
So you should better parse the code and replace those variables separately. An example:
$tokens = preg_split('/(\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i=1, $n=count($tokens); $i<$n; $i+=2) {
$name = substr($tokens[$i], 1, -1);
if (isset($variables[$name])) {
$tokens[$i] = $variables[$name];
} else {
// Error: variable missing
}
}
$string = implode('', $tokens);
It sounds like you're trying to do some template variable replacement ;)
I'd advise collecting your variables first, in an array for example, and then use something like:
// Variables are stored in $vars which is an array
foreach ($vars as $name => $value) {
$str = str_replace('{' . $name . '}', $value, $str);
}
{Not actually an answer, but need clarification}
Could you expand your question? Are you wanting to apply a regex to the contents of $variable?
The following line should replace all occurences of the string '{variable}' with the value of the global variable $variable:
$mystring = preg_replace_callback(
'/\{([a-zA-Z][\w\d]+)\}/',
create_function('$matches', 'return $GLOBALS[$matches[1]];'),
$mystring);
Edit: Replace the regex used here by the one mentioned by Gumbo to precisely catch all possible PHP variable names.
(in comments) i want to be able to type {variable}
instead of <?php echo $variable ?>
Primitive approach: You could use an external program (e.g. a Python script) to preprocess your files, making the following regex substitution:
"{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}"
with
"<?php echo $\g<1> ?>"
Better approach: Write a macro in your IDE or code editor to automatically make the substitution for you.