- Get class value and text from qualifying span tags in html document
- Javascript php html get text from span element
- How to get span text in in php variable?
- JavaScript — Get the text of a span element
- Example
- JavaScript Date Methods
- Click on the above button to get the span text
- Output
- Get class value and text from qualifying span tags in html document
- How to Get the inner text of a span in PHP
- A solution to Get span id value in PHP
- Let’s start with the solution for getting span value in PHP in a detail.
- An important step to assign to PHP :
- How to get all text nodes value between span nodes
- 2 Answers 2
- Получить значение из тега span в переменную
- Решение
Get class value and text from qualifying span tags in html document
Please help me with the following pattern for preg_match_all How to change my pattern to get the desired output? In a string search for tags with a class name like ‘ email_ ‘ ( email_ OR email_p_12 OR email_22 OR email_xx ) get the text between tags THE EMAIL ADDRESS get the classname starting with ’email_’ This is my pattern : $pattern = ‘~ What I need is an Array like this:
Array ( [0] => Array ( [mail] => labore@et.de [class] => email_p_14 ) [1] => Array ( [mail] => esse@cillum.de [class] => email_p_22 ) [2] => Array ( [mail] => anim@id.de [class] => email_ ) [3] => Array ( [mail] => laboris@nisi.de [class] => email_ ) )
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore@et.de dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea consequat. Duis aute irure in reprehenderit in voluptate velit anim@id.de laborum. Donec elementum ligula. Quis nostrud exercitation ullamco laboris@nisi.de aliquip ex ea consequat. '; /* Looking for these: labore@et.de anim@id.de laboris@nisi.de */ $pattern = '~ $val) < $output[$key][]=$val; >> print("
".print_r($output,true)."");
Array ( [0] => Array ( [0] => labore@et.de [1] => red email_p_14 [2] => labore@et.de ) [1] => Array ( [0] => esse@cillum.de [1] => email_ [2] => p_22 [3] => esse@cillum.de ) [2] => Array ( [0] => anim@id.de [1] => blue email_ green [2] => anim@id.de ) [3] => Array ( [0] => laboris@nisi.de [1] => blue email_ green black [2] => laboris@nisi.de ) )
Array ( [0] => Array ( [mail] => labore@et.de [class] => email_p_14 ) [1] => Array ( [mail] => esse@cillum.de [class] => email_p_22 ) [2] => Array ( [mail] => anim@id.de [class] => email_ ) [3] => Array ( [mail] => laboris@nisi.de [class] => email_ ) ) */
Javascript php html get text from span element
Solution 1: try this one add span text in php code to get the span value in variable Solution 2: Please try the below code and check at your end you can get class value in the array. You can make use of named capture groups to get the keys and : Regex demo | PHP demo In the result, remove the numerical keys: Output What you could also do is look into DOMDocument, find the spans that have a classname starting with email_ and then match the value of that span for an email address like pattern.
How to get span text in in php variable?
try this one add span text in php code to get the span value in variable
Please try the below code and check at your end you can get class value in the array.
loadHTML($str); $items = $DOM->getElementsByTagName('span'); $span_list = ''; for($i = 0; $i < $items->length; $i++) < $item = $items->item($i); if($item->getAttribute('class') == 'cid')< $span_list = $item->nodeValue; > > echo $span_list; ?>
Code for multiple span tags and get single value from that span list array.
loadHTML($str); $items = $DOM->getElementsByTagName('span'); $span_list = array(); for($i = 0; $i < $items->length; $i++) < $item = $items->item($i); if($item->getAttribute('class') == 'cid')< $span_list[] = $item->nodeValue; > > //get the each value for multiple span tag foreach ($span_list as $key => $value) < echo $value; echo '
'; > ?>Add an AJAX code to pass it to PHP
$.ajax(< url: 'your_php_file.php', method: 'POST', data: , success: function(result) < console.log(result); >>)
And in your PHP file. You can just use strip_tags
The Content Span element — HTML: HyperText Markup Language, It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang . It should be
JavaScript — Get the text of a span element
To get the text of the span element in JavaScript, the code is as follows −
Example
body < font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; >.sampleJavaScript Date Methods
Click on the above button to get the span text
Output
On clicking the “CLICK HERE” button −
JavaScript | Change the text of a span element, HTML DOM textContent Property: This property set/return the text content of the defined node, and all its descendants.
Get class value and text from qualifying span tags in html document
Parse html with DOMDocument and XPath. Once you have targeted the appropriate nodes, dig in and extract the data, then push the new subarrays into the result.
$dom = new DOMDocument; libxml_use_internal_errors(true); $dom->loadHTML($string); $xpath = new DOMXPath($dom); $result = []; foreach ($xpath->query("//span[starts-with(@class, 'email_') or contains(@class, ' email_')]") as $span) < $result[] = [ 'mail' =>$span->nodeValue, 'class' => preg_replace( '~.*\b(email_\S*).*~', '$1', $span->getAttribute('class') ) ]; > var_export($result);
array ( 0 => array ( 'mail' => 'labore@et.de', 'class' => 'email_p_14', ), 1 => array ( 'mail' => 'esse@cillum.de', 'class' => 'email_p_22', ), 2 => array ( 'mail' => 'anim@id.de', 'class' => 'email_', ), 3 => array ( 'mail' => 'laboris@nisi.de', 'class' => 'email_', ), )
For the class value you use this pattern ((.*?)*)*(email_(.*?))?(.*?) which uses a combination of repeating capture groups where all is actually optional.
For the email address you use (.*?) which matches any char non greedy and does not match an email like pattern.
You can make use of named capture groups to get the keys mail and class :
In the result, remove the numerical keys:
$re = '`]*\bclass="[^"]*(?email_[^\s"]*)[^"]*">\h*(?[^\s@]+@[^\s@]+)\h*`'; $str = ' labore@et.de '; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); print_r(array_filter($matches[0], function ($k) < return !is_numeric($k); >, ARRAY_FILTER_USE_KEY));
Array ( [class] => email_p_14 [mail] => labore@et.de )
What you could also do is look into DOMDocument, find the spans that have a classname starting with email_ and then match the value of that span for an email address like pattern.
Then you can build your array with the keys and values.
$str = ' labore@et.de '; $dom = new DomDocument(); $dom->loadHTML($str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $doc = new DOMXPath($dom); $items = $doc->query("//span[contains(@class, 'email_')]"); foreach ($items as $item) < $class = array_filter(explode(' ', $item->getAttribute('class')), function($x) < return substr( $x, 0, 6 ) === "email_"; >); print_r($class); echo $item->nodeValue; >
Array ( [2] => email_p_14 ) labore@et.de
JQuery | Get the text of a span element, Given an HTML document and the task is to get the text of a tag using JQuery. Method 1: Using jQuery text() Method: This method is
How to Get the inner text of a span in PHP
Ok, you’re going to need more than just PHP to get this done; you’ll need JavaScript as well.
Let’s start with your HTML. I’m assuming your rendered output looks like the following and I won’t question why you’re doing it this way.
Option One Option Two Option ThreeSo there’s my guess at your HTML.
To post a value back to PHP, you’re also going to need a way to capture the selected value in an input field that can be posted with a form. A hidden input will probably be the best option for you.
So that’s our markup done. Next you’ll need to grab the selected option from your div and stick it into the hidden field. I’m assuming you’ve coded something to render your div to look and behave exactly like a dropdown (ok, I’ll bite. Why ARE you doing it this way?).
This is the JavaScript code using jQuery (we only use jQuery on StackOverflow. Just kidding; that’s not true. Well, maybe it’s a little bit true)
Now, as long as you’ve ensured that the hidden field is contained within a form that posts back to your target PHP page, you’ll have the value of the span tag available to you.
I’ve made quite a few assumptions about how you’ve gone about setting up your page here. Correct me on any parts that don’t tie into reality.
JavaScript | Get the text of a span element, Given an HTML document and the task is to get the text of a element. There are two methods used to get the span elements which are
A solution to Get span id value in PHP
In this article, you going to see how to get span tag of html value assign to the PHP variable. We going to see in a step by step.
Let’s start with the solution for getting span value in PHP in a detail.
You going to see this with the help of example.
To store the span text into PHP variable, we going to achieve this using below example.
Below is the example from which you can understand completely.
Printed PHP variable total amount value : '.$output = $_POST['total'].''; > ?>
+
=(Store in Span id value) Rs.
With help of Student fees calculation you can understand completely.
In the above example you can see two input box one for Math fees and another one is for English fees.
I am calculating both subject fees using Jquery.
I taking both input value using Jquery and then passing into function where calculation is done.
After the completion of the calculation it is assign to html input tag element inside form.
When the total value of the both fees get inserted inside input tag name total of form.
An important step to assign to PHP :
You can see the output above.
Now step is to how the value is get populated using Jquery.
On click of submit button the form value get posted.
This posted value is get assign to PHP variable.
In this form is get posted on click of submit button and value is get assigned to PHP value.
Finally we done with the assign of span data to php variable.
This posted total variable you can also use to insert this data to into database.
To insert the posted value into database you can use the SQL statement query.
Below is syntax for SQL statement query.
INSERT INTO table_name VALUES (value1, value2, value3, value4. );Below is descriptions regarding parameter and its value.
Parameter Description value1 It is the first value to be inserted. value2 It is the second value to be inserted. value3 It is the third value to be inserted. value4 It is the fourth value to be inserted. Insert statement query
I hope you liked my this article. If you have any queries or any question regarding this, Feel free to comment on Me.
How to get all text nodes value between span nodes
You mean you are getting this content in php and want to retrieve the text along with those
tags in php file?2 Answers 2
You can query these elements using XPath, but need to do the «cleanup» of these bullet points in PHP as SimpleXML only supports XPath 1.0 without extended string editing capabilities.
Most important is the XPath expression, which I will explain in detail:
- //span[text()=’a’]/following::text() : Fetch all text nodes after the span with content «a»
- [. = //span[text()=’b’]/preceding::text()] Compare each of them to the set of text nodes before the span with content «b»
And here’s the full code, you might want to invest some more effort in removing the bullet point. Make sure PHP is evaluating it as UTF-8, otherwise you will get Mojibake instead of the bullet point.
a
• first
• Second
• second
• third
b '; libxml_use_internal_errors(true); $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->strictErrorChecking = false; $dom->recover = true; $dom->loadHTML($html); $xpath = new DOMXPath($dom); $results = $xpath->query("//span[text()='a']/following::text()[. = //span[text()='b']/preceding::text()]"); foreach ($results as $result) < $token = trim(str_replace('•', '', $result->nodeValue)); if ($token) $tokens[] = $token; > echo implode(',', $tokens); ?>Получить значение из тега span в переменную
Получить значение из тега , сравнить с имеющимся
Добрый день, уважаемые форумчане! Ввиду своих невысоких познаний и острой необходимости решить.
Как вытащить значение из безклассового тега ?
Есть вот такой кусок кода: p = urlopen(url) sp = BeautifulSoup(p.Получить значение из span
Я получаю значение span из Spring: <span th:text="$"></span> Мне нужно.Получить значение span’a
Всем привет, столкнулся с такой проблемой: не могу получить значение внутри span’a, пробовал так.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15$html = ' 2300 руб. '; # Шаблон поиска $pattern = '~price">.*(.*)~s'; # Ищем данные по шаблону preg_match( $pattern, $html, $matches ); $summ = (int) $matches[1];
lyod, спасибо, но.
цена(2300) находится на странице, ее надо сначала вытащить из этой страницы. т.е там может быть абсолютно любая сумма. Задача стоит в том, чтоб получить ее из html страницы в пхп код
Сообщение от сахей
Сообщение было отмечено сахей как решение
Решение
Сообщение от сахей