swap text/add specific word html/php code - php

I am looking to translate some very specific encoding to something that will improve its readability.
Example input
OUT PUT:
Copper Box v3;
S/N:25304;FW:1.07.12;
;a-b;a-GND;b-GND;
U=;0.74 V;3.23 V;0.48 V;
U~;0.03 V;0.02 V;0.02 V;
C;232.5 nF;11.87 nF;30.73 nF;
ISO;2.28 MΩ;237 kΩ;2.19 MΩ;
R;- -;
ΔC;- -;
Length; - m;
Desired output
OUT PUT:
U=;
A-B 0.74 V
A-G 3.23 V
B-G 0.48 V
U~;
A-B 0.03 V
A-G 0.02 V
B-G 0.02 V
C;
A-B 232.5 nF
A-G 11.87 nF
B-G 30.73 nF
ISO;
A-B 20.28 MΩ
A-G 237,1 kΩ
B-G 20.19 MΩ
Background
In my spare time I work with printed circuit boards as a hobby and try to fix broken machines for people, like coffee machines.
I have a new device with which I can measure things in an easy way.
But the device only gives a QR code that I can scan. It looks like the "example input" provided above.
I want to make it easier to read such text.
Manually changing it is a possibility; but it takes a lot of time. Sometimes I have 5 such measurements per hour.
Question
I would love to make a textarea box where I could paste it in, press a "beautify" button, and have code that makes the translation.
I was reading this, and even found a thing called the hanna code or so, but that did not give the little part I am looking for...
I know a little bit of PHP and HTML. Is there a way to use it in that language or do I need to learn how to use JavaScript or whatever?
Could you point me in the right direction? I would love to get this puzzle solved, but I don't even know where to start....

Here is a JavaScript solution. You can directly paste the output in the first box, and the second box will immediately give the beautified translation.
Of course, I had to make some assumptions about the syntax of the original text, so let me know how this meets your needs:
document.querySelector("#source").addEventListener("input", function () {
const lines = this.value.split(/^;/m).slice(1).join("").split("\n");
const cols = lines.shift().toUpperCase().split(";")
.filter(Boolean).map(code => code.slice(0,3));
document.querySelector("#target").value = "OUT PUT:\n" +
lines.filter(line => /;\d/.test(line))
.map(line => line.split(";").filter(Boolean))
.map(([s, ...v]) => s + "\n" + v.map((value, i) =>
cols[i] + " " + value
).join("\n"))
.join("\n");
});
<table>
<tr>
<th>Paste output here:</th><th>Beautified:</th>
</tr>
<tr>
<td><textarea id="source" cols="30" rows="18"></textarea></td>
<td><textarea id="target" cols="30" rows="18" readonly></textarea></td>
</tr>
</table>

Your question is very broad but reading it carefully I'm going to assume that you are not interested in a specific coding example but moreso a strategy. We're I looking at a problem like this in HTML I would without question code it in JavaScript.
The main difference between JavaScript (JS) and PHP in the example you've stated (ie, in HTML) is that PHP is a server-side language while JS is client based. This means that for PHP to solve the problem you need a webserver (a place to host the script), a way to post to the server, a PHP script on the server that can make the conversion for you.
In addition to that for the PHP solution you need a way for HTML to make the server side request to make the translation for you (translation meaning converting the first form of the data into the second) ie the HTML page needs to ask the webserver for the answer, post the original data to the server and receive (catch) the result and display it... generally this is all done in JavaScript using a technology called Ajax.
Another approach to solving the server problem w/out JavaScript is to use the HTML FORM tag with an associated INPUT to submit the data to the server. Then the server will render an entirely new page in HTML that contains the changed data and return that to the client (your web browser) replacing the old HTML page with the updated one. A lot of work!
A simpler solution would be to just use JavaScript which will allow you to do all the work in your client (the webbrowser) and will not require a webserver, re-rendering the page, etc. Far simpler and a better place to start if you're just exploring into coding - which from your question seems the case.
I would research JavaScript and some simple tutorials for reading/setting values on the page. As for how to actually code the function in JS to make the conversion of the data... that's relatively straight forward IF you can assume that the data is "fair" (ie, has no errors, bugs, etc) otherwise the problem of determining the veracity of the data is a far far more complex problem than the actual conversion (this is often the case in Computer Science).
All that said, I think it is an awesome project for starting to learn JS and think it's a great place to start. Take a look at these examples for some basics of JS and how to move data from one place to another.
https://formidableforms.com/knowledgebase/javascript-examples/

Related

Searching text in pdf using php

I am having a big database roughly it has 5 lakh (500K) entries now all those entries also have some document associated with them (i.e. every id has at least pdf file). Now I need a robust method to search for a particular text in those pdf files and if I find it, it should return the respective 'id'
kindly share some fast and optimized ways to search text in a pdf using PHP. Any idea will be appreciated.
note: Changing the pdf to text and then searching is not what I am looking for obviously, it will take a longer time.
In one line I need the best way to search for text in pdf using PHP
If this is a one-time task, there is probably no 'fast' solution.
If this is a recurring task,
Extract the text via some tool. (Sorry, I don't know of a tool.)
Store that text in a database table.
Apply a FULLTEXT index to that table.
Now the searching will be fast.
I myself wrote a website in ReactJS to search for info in PDF files (indexed books), which I indexed using Apache SOLR search engine.
What I did in React is, in essence:
queryValue = "(" + queryValueTerms.join(" OR ") + ")"
let query = "http://localhost:8983/solr/richText/select?q="
let queryElements = []
if(searchValue){
queryElements.push("text:" + queryValue)
}
...
fetch(query)
.then(res => res.json())
.then((result) =>{
setSearchResults(prepareResults(result.response.docs, result.highlighting))
setTotal(result.response.numFound)
setHasContent(result.response.numFound > 0)
})
Which results in a HTTP call:
http://localhost:8983/solr/richText/select?q=text:(chocolate%20OR%20cake)
Since this is ReactJS and just parts of code, it is of little value to you in terms of PHP, but I just wanted to demonstrate what the approach was. I guess you'd be using Curl or whatever.
Indexing itself I did in a separate service, using SolrJ, i.e. I wrote a rather small Java program that utilizes SOLR's own SolrJ library to add PDF files to SOLR index.
If you opt for indexing using Java and SolrJ (was the easiest option for me, and I didn't do Java in years previously), here are some useful resources and examples, which I collected following extensive search for my own purposes:
https://solr.apache.org/guide/8_5/using-solrj.html#using-solrj
I basically copied what's here:
https://lucidworks.com/post/indexing-with-solrj/
and tweaked it for my needs.
Tip: Since I was very rusty with Java, instead of setting classpaths etc, quick solution for me was to just copy ALL libraries from SOLR's solrj folder, to my Java project. And possibly some other libraries. May be ugly, but did the job for me.

Adding zeros after the decimal on a form

I'm hoping to solve this in pure html. I suspect a solution may not exist, and I'm willing to learn a PHP solution. If that doesn't exist either, I'll learn whatever language I must.
Take the following form for example
<form>
Price $<input type="number" name="price"><br>
</form>
It may not immediately be obvious to the user that this field accepts cents as well as dollars. (By, for example, typing 1.1 for $1.10.)
The same issue will come up when I ask a customer how many kilograms they wish to order, it won't immediately be obvious to them that they can order 100 grams by typing "0.1"
What I would like is for the field to start as ".00" with the curser appearing on the left when clicked, but as soon as the user types "." it will overwrite the existing ".". When the user types further numbers, the first two digits should overwrite the existing 0s, and further digits will be disabled.
This way, the user will be prompted to consider if they want to specify a certain number of cents (for a price) or grams (for a weight) without a condescending text field explaining what a decimal point is.
Does a html solution exist? If not, what other solutions exist? (I don't know ANY solutions.)
Example
There seems to be some confusion among my answers as to what I'm asking for, so I created a quick and dirty example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<br><br><br>
Price $<input style="text-align:right" type="number" name="price" value=".00">
</form>
</body>
</html>
(I know, style attribute inside a tag, I'm going to hell to burn for eternity.)
Using this, and photoshop, I created a simulation of the functionality I wanted, comic book style.
As shown, I already know how to get the initial state. I thought this might be possible with one quick piece of code, but if it can't, I have broken the question down into its core components below:
How do I move the cursor to a in front of the decimal point when the user clicks to the right of the decimal point?
How do I make the text overwrite the initial decimal point with a new decimal point, and have it continue to overwrite?
How do I disallow extra decimal points?
How do I disallow the user from writing more than a predetermined number of digits? (two, in the example shown above)
How do I automatically replace characters deleted (by backspace for example) with a 0?
Up-votes to anyone who can answer at least one of the questions above, or at least reveals a valuable insight towards answering one of the questions above.
Sorry, this question is getting more complex than I initially thought it was.
Update
I'm beginning to expect a PHP solution doesn't exist either. I'm still quite new to coding, so I could be completely wrong, but this is why:
PHP is a server side language, and this task requires live instantaneous functionality on the client's end without waiting for a server to validate their request to delete a decimal point.
This functionality is too specific and advanced for html and CSS. Therefore, it must be achieved through something else. I'll still leave this question up here, in case anyone wants to have a stab at the answer, but my knowledge of other languages (like JavaScript) isn't quite advanced enough to compile individual core component answers into one final functional answer... yet.
So I'm going to busy myself updating my website using the skills I have for the tasks that require doing. Even when I'm ready to learn a new language, this is too advanced a problem to tackle straight away. But, when I'm learning new functions, if I discover something that will solve this problem, I'll post the full code back here for the community to reference in future.

Running preg_replace on html code taking too long

At the risk of getting redirected to this answer (yes, I read it and spent the last 5 minutes laughing out loud at it), allow me to explain this issue, which is just one in a list of many.
My employer asked me to review a site written in PHP, using Smarty for templates and MySQL as the DBMS. It's currently running very slowly, taking up to 2 minutes (with a entirely white screen through it all, no less) to load completely.
Profiling the code with xdebug, I found a single preg_replace call that takes around 30 seconds to complete, which currently goes through all the HTML code and replaces each URL found to its SEO-friendly version. The moment it completes, it outputs all of the code to the browser. (As I said before, that's not the only issue -the code is rather old, and it shows-, but I'll focus on it for this question.)
Digging further into the code, I found that it currently looks through 1702 patterns with each appropriate match (both matches and replacements in equally-sized arrays), which would certainly account for the time it takes.
Code goes like this:
//This is just a call to a MySQL query which gets the relevant SEO-friendly URLs:
$seourls_data = $oSeoShared->getSeourls();
$url_masks = array();
$seourls = array();
foreach ($seourls_data as $seourl_data)
{
if ($seourl_data["url"])
{
$url_masks[] = "/([\"'\>\s]{1})".$site.str_replace("/", "\/", $seourl_data["url"])."([\#|\"'\s]{1})/";
$seourls[] = "$1".MAINSITE_URL.$seourl_data["seourl"]."$2";
}
}
//After filling both $url_masks and $seourls arrays, then the HTML is parsed:
$html_seo = preg_replace($url_masks, $seourls, $html);
//After it completes, $html_seo is simply echo'ed to the browser.
Now, I know the obvious answer to the problem is: don't parse HTML with a regexp. But then, how to solve this particular issue? My first attempt would probably be:
Load the (hopefully, well-formed) HTML into a DOMDocument, and then get each href attribute in each a tag, like so.
Go through each node, replacing the URL found for its appropriate match (which would probably mean using the previous regexps anyway, but on a much-reduced-size string)
???
Profit?
but I think it's most likely not the right way to solve the issue.
Any ideas or suggestions?
Thanks.
As your goal is to be SEO-friendly, using canonical tag in the target pages would tell the search engines to use your SEO-friendly urls, so you don't need to replace them in your code...
Oops ,That's really tough, bad strategy from the beginning , any way that's not your fault,
i have 2 suggestion:-
1-create a caching technique by smarty so , first HTML still generated in 2 min >
second HTMl just get from a static resource .
2- Don't Do what have to be done earlier later , so fix the system ,create a database migration that store the SEO url in a good format or generate it using titles or what ever, on my system i generate SEO links in this format ..
www.whatever.com/jobs/722/drupal-php-developer
where i use 722 as Id by parsing the url to get the right page content and (drupal-php-developer) is the title of the post or what ever
3 - ( which is not a suggestion) tell your client that project is not well engineered (if you truly believe so ) and need a re structure to boost performance .
run

PHP or JS Templateing engine? (for multiple blocks of the same html)

Main questions are in bold at the bottom, But I'll walk you through what and why i'm asking.
Basically taking what i'm now doing for users one-at-a-time, and trying to give them the option of displaying everything on one-page. Was using PHP to place data in html, but interested in improving my code and wondering if a handlebars.js with javascript would make more sense, even just for my own sanity.
Say a user has a list with check box's next to each
[x] Option 1
[ ] Option 2
[ ] Option 3
...
[x] Option 20
For each box checked, a block of html is displayed with information from the database.
Right now, I only display one block of html per page. PHP was on the same page, grabbing the data, and looping through the 2 arrays generated from two queries, with inline php inside the html to generate the current blocks of html.
....
<div class="option-wrapper">
<?php foreach ( $option_list as $option ) : ?>
....
With needing to be able to generate this same block of code between 1 and 20 times on the same page. I guess I could still use php inline and loop over the entire block of html to create another block of html for each selected option.
| Option 1 | | Option 20 |
| Title: Test1 | | Title: Test2 |
But I was wondering if there is an advantage to using a javascript templating engine for this purpose. I have javascript written to chart data, currently I have hidden html elements that store the php variables (15 of them from two arrays), which is then pulled by my jQuery. But I already feel like hiding variables in html at least feels like bad practice.
<div id="total-users" style="display:none;"><?php echo $total_users ?></div>
....
var totalUsers = $('#total-users').html();
This may be one of those, if you had to ask, it probably is bad practice type of questions. But, honestly, is this bad practice?
In the interest of writing higher quality code, would this be better done using json_encode after php grabs all of the data. Then to use a javascript template engine like handlebars.js with in a block of html that is cloned for each option that is selected?
One more thing, I may in the future want to be able to switch the data being displayed on-the-fly using a drop down in each block, does this change which route makes more sense?
Is there anything else obvious that i'm missing, or doing wrong?
Thank you!
I would absolutely recommend using a template for the data.
1- As the user selects an option (or submits their final choices from all available options), make an AJAX call to retrieve a JSON object (you can return one object or all option data in one JSON call, the latter preferred).
2- Use the template (handlebars, moustache, underscore, etc), to render the data in a success callback function.
This will make your code more efficient, and more flexible for future UI requests (your code would support many different implementations from a user experience standpoint).
If I understand you correctly, the information you're retrieving from the database is static (that is, it doesn't change between each checkbox click).
If the above is true, I would personally do it like this. (just my opinion though)
I would grab all information from the database (referring to all "checkboxes") just once, server-side (PHP). Then I would put them in hidden divs:
<div id="stuffFromDb1" class="hidden" style="display: none">blablabla</div>
Then, when the user clicks in a checkbox, I would show the correspondent div, by changing the display: none to display: block. (with jQuery it's even easier, see Toggle.
This seems to me the most efficient way instead of grabbing the information through AJAX or multiple "forms".
EDIT:
I prefer this method to AJAX and form post because it reduces the number of requests to the server. Unless the DB queries are very CPU intensive (complicated) it is usually faster to query the database once than several times and giving the user a better experience.
Edit2:
It's hard to give you an answer without seeing the code but for 100 or 200 or even 1000, I would bet it would be faster overall to load them all at once than loading them 1 by 1, Specially if you could achieve that doing only 1 query to the database.
Client side template system always relies on the speed of the client. In newer browsers / new PCs JS engine is fairly quick, but for older PCS / older browsers that is not true at all. Complex DOM manipulations + the time needed to complete the AJAX request may take quite a while, a time during which the user may not be able to interact with the page. Besides, other problems might arise (AJAX Race Condition pops into my mind).

using php to get two even columns of text

Does anyone know a clever way to create even columns of text using php?
So lets say I have a few paragraphs of text and I want to split this into two columns of even length (not string length, I'm talking even visible length).
At the moment I'm splitting based on word count, which (as you can imagine) isn't working too well. For instance, on one page I have a list (ul li style) which is increasing the line breaks but not the word count. eg: whats happening is that the left column (with the list in it) is visibly longer than the right column (and if there was a list in the right hand column then it would be the same the other way round).
So does anyone have a clever way to split text? For instance using my knowledge of objective c there is a "size that fits" function. I know how wide the columns are going to be, so is there any way to take that, and the string, and work out how high its going to be? Then cut it in half? Or similar?
Thanks
ps: no css3 nonsense please, we're targeting browsers as far back as ie6 (shudder). :)
I know you're looking at a PHP solution but since the number of lines will depend on how it's rendered in the browser, you'll need to use some javascript.
You basically need to know the dimensions of the container the text is in and using the height divided by the text's line-height, you'll get the number of lines.
Here's a fiddle using jQuery: http://jsfiddle.net/bh8ZR/
There is not a lot of information here as to the source data. However, if you know that you have 20 lines of data, and want to split it, why not simply use an array of the display lines, then divide by two. Then you can take the first half of the PHP array and push it into the second column when you hit the limit of the first.
I think you're going to have trouble displaying these columns in a web browser and having a consistent look and feel because you're trying to apply simple programming logic to a visual layout. CSS and jQuery were designed to help layout issues. jQuery does have IE6 compatibility.
I really don't think you're going to find a magic bullet here if you have HTML formatting inside the data you're trying to display. The browser is going to render this based on a lot of variables. Page width, font size, etc. This is exactly why CSS and other layout styles are there, to handle this sort of formatting.
Is there any reason why you're not trying to solve this in the browser instead of PHP? IE6 to me is not a strong enough case not to do this where it belongs.

Categories