Substring a text since the target founded - preg-replace

I have a search on my php page and it is ok.
With my search result, I highlighted the string target on my content.
$search_tag_text = #preg_replace("/($mysearch)/i", "<u style=\"color:red\">$1</u>", $row->txtContent);
Ok, but is it possible, after having found a string target on my content, to show 20 words before and 20 words after, instead listing all my content?
Any help will be appreciated.

I would try something like:
$matches = array();
preg_match("/($mysearch)/i", $search_tag_text, $matches, PREG_OFFSET_CAPTURE);
And then in the match you would have the offset of where the found string is, then you could do:
$search_tag_text = substr($subject, ($matches[0][1] - 30), 60);
For 30 characters before the match and 30 after. If i've understood correctly the last element in $mathces[i][x] is the offset where the match was found.

Related

Flutter: how to split a list of string that contain html tags using regex?

I try to split the list of sentences which have html tags as below:
The sky is clear and the stars are twinkling.
They were excited to see their first sloth.
Douglas figured the best way to succeed was to do the opposite of what he'd been doing all his life.
The result I want is as below:
[The, sky, is clear and the, stars, are twinkling.]
[They were, excited, to see their first sloth.]
[Douglas figured the best way to, succeed, was to do the, opposite, of what he'd been doing all his life.]
How am I able to do it with RegExp in order to get above result?
For example this is your string:
String str =
"The sky is clear and the stars are twinkling. They were excited to see their first sloth. Douglas figured the best way to succeed was to do the opposite of what he'd been doing all his life.";
you clan split it like this:
final reg = RegExp("<[^>]*>");
var result = str.split(reg);
print('result = $result'); // [The , sky, is clear and the , stars, are twinkling. They were , excited, to see their first sloth. Douglas figured the best way to , succeed, was to do the , opposite, of what he'd been doing all his life.]
if you want it with tag, try this(tanks to #JovenDev):
final reg = RegExp("(?=<a)|(?<=/a>)");
var result = str.split(reg);
print('result = $result'); // [The , sky, is clear and the , stars, are twinkling. They were , excited, to see their first sloth. Douglas figured the best way to , succeed, was to do the , opposite, of what he'd been doing all his life.]

Sorting files in alphabetical order [duplicate]

This question already has answers here:
Is there a way to sort string lists by numbers inside of the strings?
(2 answers)
Closed 2 years ago.
I have a list of files like this :
['../page-1.png', '../page-3/png', '../page-2.png', '../page-6.png', ... '../page-9.png']
I need to sort these files according to the number at the end. I am using this :
imagePaths.sort((a, b) =>
a.toString().toLowerCase().compareTo(b.toString().toLowerCase()));
where imagePaths is the list of paths of those images.
THE ISSUE
This method works fine until there are only single digit file numbers, i.e. if there is a file called, '../page-10.png', it gets sorted into the list like so :
['../page-1.png', '../page-10.png', '../page-11.png', '../page-12.png', '../page-2.png', ..]
Now, how to sort them in their correct order?
I think I could give you an idea.
If the name pattern remains the same, then this gonna work out!
var pages = [
'../page-1.png',
'../page-2.png',
'../page-11.png',
'../page-12.png',
'../page-10.png',
];
pages.sort((a, b) =>
int.parse(a.split('-')[1].split('.')[0]).compareTo(int.parse(b.split('-')[1].split('.')[0])));
print(pages);
// [../page-1.png, ../page-2.png, ../page-10.png, ../page-11.png, ../page-12.png]
Just splitting the string and parsing the number and then sorting it.
Reference: https://api.dart.dev/stable/2.10.4/dart-core/Pattern-class.html
Hope that works!
A clean and safe solution will be by using a regex to extract the numbers instead of relying on the name format:
int parse(String page) {
return int.tryParse(page.split(RegExp(r'[^\d]')).singleWhere((value) => int.tryParse(value) != null));
}
list.sort((a, b) => parse(a) > parse(b) ? 1 : -1);
Whist there are technical solutions to this, as per the other answers, the fundamental problem is that the files are not being named correctly if the intention is to sort them by name at some point. The numeric portion of the name should be given sufficient leading zeroes to handle the maximum number of files eg. page-0001.png, page-0002.png, etc.

Display certain number of letters

I have a word that is being displayed into a label. Could I program it, where it will only show the last 2 characters of the word, or the the first 3 only? How can I do this?
Swift's string APIs can be a little confusing. You get access to the characters of a string via its characters property, on which you can then use prefix() or suffix() to get the substring you want. That subset of characters needs to be converted back to a String:
let str = "Hello, world!"
// first three characters:
let prefixSubstring = String(str.characters.prefix(3))
// last two characters:
let suffixSubstring = String(str.characters.suffix(2))
I agree it is definitely confusing working with String indexing in Swift and they have changed a little bit from Swift 1 to 2 making googling a bit of a challenge but it can actually be quite simple once you get a hang of the methods. You basically need to make it into a two-step process:
1) Find the index you need
2) Advance from there
For example:
let sampleString = "HelloWorld"
let lastThreeindex = sampleString.endIndex.advancedBy(-3)
sampleString.substringFromIndex(lastThreeindex) //prints rld
let secondIndex = sampleString.startIndex.advancedBy(2)
sampleString.substringToIndex(secondIndex) //prints He

Power Query - remove characters from number values

I have a table field where the data contains our memberID numbers followed by character or character + number strings
For example:
My Data
1234567Z1
2345T10
222222T10Z1
111
111A
Should Become
123456
12345
222222
111
111
I want to get just the member number (as shown in Should Become above). I.E. all the digits that are LEFT of the first character.
As the length of the member number can be different for each person (the first 1 to 7 digit) and the letters used can be different (a to z, 0 to 8 characters long), I don't think I can SPLIT the field.
Right now, in Power Query, I do 27 search and replace commands to clean this data (e.g. find T10 replace with nothing, find T20 replace with nothing, etc)
Can anyone suggest a better way to achieve this?
I did successfully create a formula for this in Excel...but I am now trying to do this in Power Query and I don't know how to convert the formula - nor am I sure this is the most efficient solution.
=iferror(value(left([MEMBERID],7)),
iferror(value(left([MEMBERID],6)),
iferror(value(left([MEMBERID],5)),
iferror(value(left([MEMBERID],4)),
iferror(value(left([MEMBERID],3)),0)
)
)
)
)
Thanks
There are likely several ways to do this. Here's one way:
Create a query Letters:
let
Source = { "a" .. "z" } & { "A" .. "Z" }
in
Source
Create a query GetFirstLetterIndex:
let
Source = (text) => let
// For each letter find out where it shows up in the text. If it doesn't show up, we will have a -1 in the list. Make that positive so that we return the index of the first letter which shows up.
firstLetterIndex = List.Transform(Letters, each let pos = Text.PositionOf(text, _), correctedPos = if pos < 0 then Text.Length(text) else pos in correctedPos),
minimumIndex = List.Min(firstLetterIndex)
in minimumIndex
in
Source
In the table containing your data, add a custom column with this formula:
Text.Range([ColumnWithData], 0, GetFirstLetterIndex([ColumnWithData]))
That formula will take everything from your data text until the first letter.

Check if textfield text is almost equal to string

I have a UITextField called textfield. And I have this code to check if the text in the textfield is equal to "exampletext"
if ([textfield.text isEqualToString:#"exampletext"]) {
NSLog(#"Correct");
} else {
NSLog(#"Wrong");
}
But I also want to check if the text in the textfield is almost equal to "exampletext", if the text is almost the same as "exampletext". Like if the text was "eampletex" I want to NSLog(#"Close")
Are there any ways to check if the textfield text is like 50% equal to "exampletext"?
Or any ways to check if the textfield text has 50% the same characters as "exampletext"?
Or something else like that?
What you are looking for is an implementation of the levenshtein distance, levenshtein("hello", "hallo") => 1, levenshtein("hello", "ellos") => 2. You can check this library.
Once you have the distance between the two strings, you could get it as a percentage calculating: percentage = 100 * levenshtein(original,other) / length(original)
Here's my go at it. Create a custom character set from the string you want to match. Check each character in the texfield.text against that character set, and if the number of matches is close to the number of letters in the string, do something..
NSString *testString = #"wordToCompare";
NSString *textFromTextfield = textfield.text;
//create a custom character set from the word you want to compare to...
NSCharacterSet *characterSetForString = [NSCharacterSet characterSetWithCharactersInString:testString];
//keep track of how many matches...
int numberOfCharsThatMatchSet = 0;
for (int x = 0; x < [textFromTextField length]; x++) {
unichar charToCheck = [textFromTextField characterAtIndex:x];
if ([characterSetForString characterIsMember:charToCheck] == YES) {
numberOfCharsThatMatchSet++;
}
NSLog(#"%d", numberOfCharsThatMatchSet);
}
// if the number of matches is the same as the length of the word + or - 2...
if ((numberOfCharsThatMatchSet > [testString length] - 2 ) && (numberOfCharsThatMatchSet < [testString length] + 2 )) {
NSLog(#"close match...");
}
Not sure if this is 100% what you're looking for, but maybe it will help anyway...
I'm sure there might be some open source out there somewhere that would do this for you..however, one approach I can think of that will give you a bit of a lead...
Sort out the characters of both your strings into arrays. Determine which string you want to be the master string and grab the string length of it.
Now compare each character. Ex: Word 1: hello, Word 2: ello.
Each time a letter is found add one to a count. If by the end of your looping your count is 80% of the original length you grabbed from the master string or greater then you most likely have a partial match.
So for our example Word 1 will be our master string and its length is 5. "ello" contains 4/5 characters and therefore is matches 80% of the original string.
I don't think there is an easy way (with several lines of code) of solving this. There are several algorithms you might consider and pick the one which suits your needs most.
You should look at this question. Although it has been designed and answered for another language, you asked for a way or method so you have your solution there.